一.跳出循环
a=True
while a:
b= input('type somesthing')
if b=='1':
a= False
else:
pass
print ('finish run')
''''
type somesthing:2
still in while
type somesthing:3
still in while
type somesthing:1
still in while #会执行下面的语句再跳出
finish run
''''
True
and False
,当输入1
时,a=False
时,会执行接下来的语句后再跳出这个循环。
二.Break
break
用法,在循环语句中,使用 break
, 当符合跳出条件时,会直接结束循环,这是 break
和 True False
的区别。
while True:
b= input('type somesthing:')
if b=='1':
break
else:
pass
print('still in while')
print ('finish run')
"""
type somesthing:4
still in while
type somesthing:5
still in while
type somesthing:1
finish run
"""
三.continue
while True:
b=input('input somesthing:')
if b=='1':
continue
else:
pass
print('still in while' )
print ('finish run')
"""
input somesthing:3
still in while
input somesthing:1 # 没有"still in while"。直接进入下一次循环
input somesthing:4
still in while
input somesthing:
"""
在代码中,满足b=1
的条件时,因为使用了 continue
, python
不会执行 else
后面的代码,而会直接进入下一次循环。
四.错误处理
输出错误:try:
, except ... as ...:
看如下代码 :
try:
file=open('eeee.txt','r') #会报错的代码
except Exception as e: # 将报错存储在 e 中
print(e)
"""
[Errno 2] No such file or directory: 'eeee.txt'
"""
首先报错:没有这样的文件No such file or directory
. 然后决定是否输入y
, 输入y
以后,系统就会新建一个文件(要用写入的类型),再次运行后,文件中就会写入ssss :
try:
file=open('eeee.txt','r+')
except Exception as e:
print(e)
response = input('do you want to create a new file:')
if response=='y':
file=open('eeee.txt','w')
else:
pass
else:
file.write('ssss')
file.close()
"""
[Errno 2] No such file or directory: 'eeee.txt'
do you want to create a new file:y
ssss #eeee.txt中会写入'ssss'
五.zip
zip
函数接受任意多个(包括0个和1个)序列作为参数,合并后返回一个tuple
列表,请看示例:
a=[1,2,3]
b=[4,5,6]
ab=zip(a,b)
print(list(ab)) #需要加list来可视化这个功能
for i,j in zip(a,b):
print(i/2,j*2)
"""
0.5 8
1.0 10
1.5 12
"""
六.lambda
lambda
定义一个简单的函数,实现简化代码的功能,看代码会更好理解。
fun = lambda x,y : x+y
, 冒号前的x,y
为自变量,冒号后x+y
为具体运算。
fun= lambda x,y:x+y
x=int(input('x=')) #这里要定义int整数,否则会默认为字符串
y=int(input('y='))
print(fun(x,y))
"""
x=6
y=6
12
"""
七.map
map
是把函数和参数绑定在一起。
>>> def fun(x,y):
return (x+y)
>>> list(map(fun,[1],[2]))
"""
[3]
"""
>>> list(map(fun,[1,2],[3,4]))
"""
[4,6]
"""