Python条件、循环和其他语句

来源:互联网 发布:云收银软件 编辑:程序博客网 时间:2024/05/24 06:04
1、print
#print():打印的表达式,不管是字符串还是其他类型进行自动转换后的字符串
>>> print('Age:',42)
Age: 42




2、import
#import:把某件事作为另一件事导入,格式如下:
1、import somemodule
2、from somemodule import somefunctio
3、from somedule import somefunction,anotherfunction,yetanotherfunction
4、from somedule import *




#提供别名,在语句末尾增加一个as子句
>>> import math as foobar
>>> foobar.sqrt(4)
2.0




>>> from math import sqrt as foobar #为函数提供别名
>>> foobar(4)
2.0




#as来进行重命名,解决不同模块,相同函数名问题
from module1 import open as open1  
from module2 import open as open2




3、赋值
>>> x,y,z =1,2,3   #多个变量赋值
>>> print(x,y,z)
1 2 3




>>> x,y=y,x   #两个变量交换
>>> print(x,y,z)
2 1 3




#序列解包:将多个值的序列解开,然后放到变量的序列中
>>> values =1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values
>>> x
1




#链式赋值:将同一个值赋给多个变量的捷径
>>> x=y=somefunction()
#增量赋值:表达式运算符放置在赋值运算符=的左边,写成x+=1
>>> x=2
>>> x+=1
>>> x*=2
>>> x
6




#对于其他数据类型也适用
>>> fnord='foo'
>>> fnord+='bar'
>>> fnord
'foobar'
>>> fnord*=2
>>> fnord
'foobarfoobar'




4、语句块:
#使用tab字符可以缩进语句块,一个tab字符位置为8个空格




5、is:同一性运算符
>>> x=y=[1,2,3]
>>> z=[1,2,3]
>>> x==y
True
>>> x==z
True
>>> x is y  #x和y值相等,并且是同一对象
True
>>> x is z  #is运算符是判定同一性而不是相等性,x 和z值相等,但不是同一对象
False
总结:使用==运算符来判定两个对象是否相等,使用is判定两者是否等同(同一个对象)




6、in:成员资格运算符
name = input('what is your name? ')
if 's' in name:
    print('your name contains the letter "s". ')
else:
    print('your name does not contain the letter "s" .')




7、断言:语句中使用的关键字是assert,在错误条件出现时,直接让程序崩溃
>>> age = -1
>>> assert 0<age<100
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    assert 0<age<100
AssertionError




>>> age=-1
>>> assert 0<age<100 , 'The age must be realistic'  #条件后可以添加字符串,用来解释断言:
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    assert 0<age<100 , 'The age must be realistic'
AssertionError: The age must be realistic




8、while循环
x=1
while x<=100:      #打印1到100的整数
    print(x)
    x+=1




9、for循环
words = ['this','is','an','ex','parrot']
for word in words:
    print(word)
输出:
>>> 
this
is
an
ex
parrot
>>> 




range(0,10)
for number in range(0,10):
    print(number)




#循环遍历字典元素
d={'x': 1,'y': 2,'z':3}
for key in d:
    print(key, 'corresponds to', d[key])
>>> 
y corresponds to 2
x corresponds to 1
z corresponds to 3
>>> 
#另一种写法:
d={'x': 1,'y': 2,'z':3}
for key,value in d.items():
    print(key, 'corresponds to', d[key])
>>> 
y corresponds to 2
x corresponds to 1
z corresponds to 3
>>> 




10、迭代工具
a、并行迭代--zip()
names = ['anne','beth','george','damon']
ages = [12,45,32,102]
for i in range(len(names)):    #打印名字和对应的年龄,i是循环索引的标准变量名
    print(names[i], 'is', ages[i], 'years od')
>>> #结果
anne is 12 years od
beth is 45 years od
george is 32 years od
damon is 102 years od
>>> 
#内建的zip函数可以用来并行迭代,把2个序列‘压缩’在一起,返回一个元祖的列表
>>> zip(names, ages)  
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]  
>>> for name, age in zip(names, ages):  
    print name, 'is', age, 'years old'   
#结果   
anne is 12 years old  
beth is 45 years old  
george is 32 years old  
damon is 102 years old  




11、编号迭代--enumerate()
一般方法:
#找到'aaa'并修改为'AAA'
['[AAA]', 'bbb', 'ccc', 'ddd']
>>> strings =['aaa','bbb','ccc','ddd']
>>> index =0
>>> for string in strings:  #注意是string而不是strings
if 'aaa' in string:
strings[index]='[AAA]'
index +=1





>>> strings
['[AAA]', 'bbb', 'ccc', 'ddd']




#使用内建的enumerate()函数
>>> strings =['aaa','bbb','ccc','ddd']
>>> for index,string in enumerate(strings):  #enumerate函数可以提供索引的地方迭代索引-值对
if 'aaa' in string:
strings[index]='AAA'





>>> strings
['AAA', 'bbb', 'ccc', 'ddd']




12、翻转和排序迭代--reversed()和sorted(),对副本进行修改,原对象不变
>>> sorted([4,3,6,8,3])
[3, 3, 4, 6, 8]
>>> reversed('Hello, world!')   #返回对象  
<reversed object at 0x013FE830>
>>> list(reversed('Hello, world!'))  #将对象转为列表  
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
>>>




13、带有步长的range(),用来跳过某些数字,或逆序
>>> range(0,10,2) #第三个参数表示步长
range(0, 10, 2)
>>> range(10,0,-1)
range(10, 0, -1)




14、break--跳出当前循环
>>> from math import sqrt
>>> for n in range(99,0,-1):
root = sqrt(n)
if root == int(root):
print(n)
break




#输出
81




15、while,break
>>> while True:
word = input('Please enter a word: ')
if not word: break   #当用户不输入是,word为空,所以为false  
print('The word was' + word)





Please enter a word: wangsf
The word waswangsf
Please enter a word: 
>>> 




16、for else
>>> from math import sqrt
>>> for n in range(99,81,-1):  #99~80,不包括81 
root = sqrt(n)
if root == int(root):
print(n)
break
else:       #只有当break不执行时,才执行else  
print("Didn't find it!")




#输出
Didn't find it!




17、类表推导式:利用其他列表创建新列表
类似for循环
>>> [x*x for x in range(10)] #类似for循环
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]




if语句
>>> [x*x for x in range(10) if x%3 == 0] #增加if语句
[0, 9, 36, 81]




多个for语句
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]




多个for语句+if语句
>>> girls = ['alice','bernice','clarice']
>>> boys = ['chris','arnold','bob']
>>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]]
['chris+clarice', 'arnold+alice', 'bob+bernice']




18、pass,del和exec
pass:什么都没发生,用做占位符
>>> pass
>>> 




>>> if name == 'Ralph Auldus Melish':
print('Welcome!')
elif name == 'Enid':
# 还没完.....
pass          #占位符
elif name == 'Bill Gates':
print('Access Denied')




19、del
X和Y都绑定到同一个字典上,当X赋值为None,字典Y还可以用,但是当Y也赋值为None,字典就漂浮在内存里面
没有名字绑定在它上面,python解释器自动删除。但是,名字a和b仍存在
>>> X=Y={'age':42,'phone': '6808','address': '上海'}
>>> X=None
>>> Y
{'phone': '6808', 'age': 42, 'address': '上海'}
>>> Y=None




del不仅删除引用,也删除名字,但原对象不会被删除,也无法手动删除只有当原对象不再被使用时,python解释器才会自动回收
>>> x=["Hello","world"]
>>> y=x
>>> y[1]="python"
>>> x   #可以修改  
['Hello', 'python']
>>> del x  #删除x,只是将x的引用和x名字删除,而原来的列表不便无法删除, 实际上不需要人为删除,当不用时python解释器会自动回收 
>>> x
Traceback (most recent call last):
  File "<pyshell#157>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>> y
['Hello', 'python']




20、使用exec和eval执行和求值字符串
python3.0中将exec变成了函数
eval--类似exec,但是执行Python表达式
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6+18*2
42
#eval语句提供2个命名空间,一个全局的一个局部的,全局的必须是字典,局部的可以是任何形式的映射
>>> scpoe={}
>>> scope={}
>>> scope['x']=2
>>> scope['y']=3
>>> eval('x*y',scope)

6



0 0