- 1.
scoundrel={'name':'Grubby','girlfirend':'Mary'}
key,value=scoundrel.popitem()
print key
print value
这里popitem方法会弹出字典里随机的项,并以元组形式返回,那么这个元组就可以直接赋值到两个变量中。
输出结果:
girlfirend
Mary
- 2.
>>> x=2
>>> x+=1
>>> x*=2
>>> x
6
>>> str='fun'
>>> str+='ction'
>>> str*=2
>>> str
'functionfunction'
增量赋值语句,可以是代码更加简洁。
- 3.
num=input('Input a number:')
if num>0:
print repr(num)+'>0'
print 'Your number is >0'
elif num<0:
print repr(num)+'<0'
print 'Your number is <0'
else:
print repr(num)+'=0'
print 'Your number is =0'
条件语句的应用。
Input a number:5
5>0
Your number is >0
- 4.
x=[1,2,3]
y=[1,2,3]
print x==y
print x is y
“==”号比较值,“is”比较是否为同一对象。
True
False
- 5.
num=input('Please input a number:')
assert 0<num<10,'Input Wrong!'
print num
这里assert的作用在于检查num的值,如果没在后面第一个参数的范围内,程序直接崩溃并输出第二个参数。
- 6.
words=list('Hello')
for word in words:
print word
print '-'*15
i=0
while i<5:
print words[i]
i+=1
print range(1,10)
简单的循环语句,while指定循环次数,for可以“量体裁衣”,按照序列中元素个数循环和range函数的使用。
H
e
l
l
o
---------------
H
e
l
l
o
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- 7.
number={'name':'Bob','age':'42'}
for key in number:
print key,'corresponds to',number[key]
遍历字典。
age corresponds to 42
name corresponds to Bob
- 8.
names=['Bob','Mary','Ruby','Smith']
ages=['12','23','24','45']
for i in range(len(names)):
print names[i],'is',ages[i],'years old.'
print '-'*25
zip(names,ages)
for name,age in zip(names,ages):
print name,'is',age,'years old.'
这里提供了两种方法对两个序列进行了对应输出。
Bob is 12 years old.
Mary is 23 years old.
Ruby is 24 years old.
Smith is 45 years old.
-------------------------
Bob is 12 years old.
Mary is 23 years old.
Ruby is 24 years old.
Smith is 45 years old.
- 9.
strings=['My', 'name', 'is', 'Bob.']
print strings
index=0
for string in strings:
if 'name' in string:
strings[index]='your'
index+=1
print strings
按索引迭代,此程序为修改字符串序列中的’name’为’your’。
['My', 'name', 'is', 'Bob.']
['My', 'your', 'is', 'Bob.']