1.要么怎样,要么不怎样 if else
2.干完了能怎样,干不完就别怎样 for while else
else只循环完成后执行,如果循环使用了break语句跳出了循环,else语句是不会执行的
3.没有问题,那就干吧
如果try 语句里没有任何异常就会执行else中的语句
4.简洁的with语句 自动关闭文件的问题
要么怎样,要么不怎样 if else
>>> if 1 > 3:
.. print(‘True‘)
... else:
... print(‘False‘)
...
False
干完了能怎样,干不完就别怎样 for while else
def showMaxFactory(num): count = num // 2 while count > 1: if(num % count == 0): print(‘%d 最大的约数是 %d‘ %(num,count)) break count -= 1 else: print(‘%d 是素数!‘ % num) num = int(input(‘请输入一个数:‘)) showMaxFactory(num)
运行结果:
[[email protected] ~]$ python3 maxFactory.py
请输入一个数:3
3 是素数!
没有问题,那就干吧
try: int(‘abc‘) except ValueError as reason: print(‘出错拉:‘ + str(reason)) else: print(‘没有任何异常‘)
运行结果:
[[email protected] ~]$ python3 test.py
出错拉:invalid literal for int() with base 10: ‘abc‘
try: int(‘123‘) except ValueError as reason: print(‘出错拉:‘ + str(reason)) else: print(‘没有任何异常‘)
运行结果:
[[email protected] ~]$ python3 test.py
没有任何异常
简介的with语句
try: f = open(‘data.txt‘, ‘w‘) for each_line in f: print(each_line) except OSError as reason: print(‘出错拉:‘ + str(reason)) finally: f.close()
运行结果:
[[email protected] ~]$ python3 test.py
出错拉:not readable
with自动关闭文件
try: with open(‘data.txt‘, ‘w‘) as f: for each_line in f: print(each_line) except OSError as reason: print(‘出错拉:‘ + str(reason))
运行结果:
[[email protected] ~]$ python3 test.py
出错拉:not readable
时间: 2024-11-05 17:21:02