今天有点头痛,所以就少学一点吧。
>>> supplies = ['pens', ' staplers', 'flame- throwers', ' binders'] #定义一个列表,有四个值
>>> for i in range (len(supplies)): #循环取变量supplies的长度
print(' Index ' + str(i) + ' in supplies is: ' + supplies [i]) #打印i的值,和对应的列表项。
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame- throwers
Index 3 in supplies is: binders
上面的这些是结果
在前面的循环中使用range(len(supplies))很方便,这是因为,循环中的代码可以访问下标(通过变量i),以及下标处的值(通过supplies[i])。最妙的是,range(len(supplies))将迭代supplies的所有下标,无论它包含多少表项。
myPets=['Zophie','Pooka','Fat-tail']
print('Enter a pet name:')
name=input()
if name not in myPets: #如果name变量的内容不在myPets里
print('I do not have a pet named '+name )
else:
print(name+' is my pet.')
Enter a pet name:
pook
I do not have a pet named pook
Enter a pet name:
Pooka
Pooka is my pet.
>>> cat=['fat', 'black', 'loud']
>>> size,color,disposition=cat #多重赋值,变量的数目和列表的长度必须严格相等,否则Python将给出ValueError:
>>> size
'fat'
>>> color
'black'
>>> disposition
'loud'
>>> spam=42
>>> spam=spam+1
>>> spam
43
>>> spam=42
>>> spam+=1
>>> spam
43
spam=spam+1和spam+=1相等,是一种快捷方式。
增强的赋值语句 等同于
spam+=1 spam=spam+1
spam-=1 spam=spam-1
spam*=1 spam=spam*1
spam/=1 spam=spam/1
spam%=1 spam=spam%1
今天就先到这里吧,明天继续。