Python_7
来源:互联网 发布:美工需要学哪些东西 编辑:程序博客网 时间:2024/06/05 15:51
- 1.
scoundrel={'name':'Grubby','girlfirend':'Mary'}key,value=scoundrel.popitem()print keyprint value
这里popitem方法会弹出字典里随机的项,并以元组形式返回,那么这个元组就可以直接赋值到两个变量中。
输出结果:
girlfirendMary
- 2.
>>> x=2>>> x+=1>>> x*=2>>> x6>>> 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:55>0Your number is >0
- 4.
x=[1,2,3]y=[1,2,3]print x==yprint x is y
“==”号比较值,“is”比较是否为同一对象。
TrueFalse
- 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 wordprint '-'*15i=0while i<5: print words[i] i+=1print range(1,10)
简单的循环语句,while指定循环次数,for可以“量体裁衣”,按照序列中元素个数循环和range函数的使用。
Hello---------------Hello[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 42name 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 '-'*25zip(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 stringsindex=0for string in strings: if 'name' in string: strings[index]='your' index+=1print strings
按索引迭代,此程序为修改字符串序列中的’name’为’your’。
['My', 'name', 'is', 'Bob.']['My', 'your', 'is', 'Bob.']