莫烦python基础教程(十)

跳出循环和错误处理

跳出循环的两种方法


break

  • 在循环语句中,使用 break, 当符合跳出条件时,会直接结束循环。
while True:
    b = input('type something:')
    if b == '1':
        break
    else:
        pass
    print('still in while')
print('finish run')

>>> 
type something:4
still in while
type something:5
still in while
type something:1
finish run

continue

  • 在循环语句中,使用 continue,当符合跳出条件时,只会结束当前循环。
  • 在下列代码中,满足b=1的条件时,因为使用了 continue,python 不会执行 else 后面的代码,而会直接进入下一次循环。
while True:
    b = input('type something:')
    if b == '1':
        continue
    else:
        pass
    print('still in while')
print('finish run')

>>>
type something:3
still in while
type something:1
type something:4
still in while

错误处理


try 错误处理

  • 输出错误:try:,except … as …: 。
try:
    file = open('eeee.txt', 'r')    # 会报错的代码
except Exception as e:  # 将报错存储在e中
    print(e)
  • 处理错误:会使用到循环语句。首先报错:没有这样的文件No such file or directory。然后决定是否输入y,输入y以后,系统就会新建一个文件(要用写入的类型),再次运行后,文件中就会写入ssss。
try:
    file = open('eeee.txt', 'r')    # 会报错的代码,第二次要将r改成r+
except Exception as e:  # 将报错存储在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()

猜你喜欢

转载自blog.csdn.net/faker1895/article/details/81938118
今日推荐