1. print和import的更多信息
(1)使用逗号输出
使用print打印多个表达式,用逗号隔开:
>>>print ‘Age:’ ,42
age: 42
(2)把某件事作为另一件事导入
import somemodule
from somemodule import somefunction
from somemodule import *
只有确定自己想要从给定的模块导入所有功能时,才应使用最后一个版本。
在语句末尾增加一个as子句,在该子句后给出名字,则为整个模块提供别名:
>>>import math as foobar
>>>foobar.sqrt(4)
2.0
也可以为函数提供别名:
>>>from math import sqrt as foobar
>>>foobar(4)
2.0
2. 赋值语句
(1)序列解包
多个赋值语句可以同时进行
>>> x,y,z = 1,2,3
交换两个(或多个)变量
>>>x,y=y,x
>>>print x,y,z
2 1 3
(2)链式赋值
x=y=somefunction()
和下面的效果相同
y=somefunction()
x=y
(3)序列解包
if语句
name = raw_input(‘What is your name? ‘)
if name.endswith(‘Gumby’):
print ‘Hello,Mr, Gumby ‘ #为真则执行语句块
in 成员资格运算符
name = raw_input(‘What is your name? ‘ )
if ‘s’in name:
print‘Your name contains the letter “s”. ‘
else
print‘Your name does not contains the letter “s”. ‘
布尔运算符number = input(‘ Enter a number between 1and 10: ‘)
if number <=10 and number >=1:
print ‘Great!’
else:
print ‘Wrong!’
number = input(‘ Enter a number between 1and 10: ‘)
if number <=10 and number >=1:
print ‘Great!’
else:
print ‘Wrong!’
断言
用assert可要求某些条件必须为真,若为假则让程序直接崩溃
>>> age=10
>>>assert 0<age<100
while循环
name = ‘ ‘
while not name:
name= raw_input(‘Please enter your name: ‘)
print ‘Hello, %s! ‘ %name
for循环
for x in…循环是把每个元素代入变量x,然后执行缩进块的语句。
sum=0
for x in range(1,101):
sum=sum+x
print sum
遍历字典元素
d={‘x’:1, ’y’:2, ’z’:3}
for key in d:
printkey, ‘corresponds to ‘, d[key]
break
#寻找100内,最大平方数
from math impoet sqrt
for n in range(99,0,-1):
root= sqrt(n)
ifroot == int(root):
printn
break
while True/break
while True:
word= raw_input(‘Please enter a word : ‘)
ifnot word:
break
print‘The word was ‘ + word
列表推导式
>>>[x*x for x in range(10)]
[0,1,4,9,16,25,36,49,64,81]
>>>[x*x for x in range(10) if x %3 ==0]
[0,9,36,81]
更多for语句
>>>[x*x for xin range(3) for y in rang(3)]
[(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]