Python基础学习(九) ------ 循环跳出 / 错误处理 / zip / lambda / map

一.跳出循环

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]
"""

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值