Try-Except语句
try:
f=open('我为什么是一个文档.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件打开时出错了\n 错误原因是:'+str(reason))
文件打开时出错了
错误原因是:[Errno 2] No such file or directory: '我为什么是一个文档.txt'
针对不同异常设置多个except
try:
int('abc')
sum = 1+'1'
f = open('我是一个不存在的文档.txt')
print(f.read())
f.close()
except (ValueError,TypeError,OSError) as reason:
print('出错了TAT\n错误原因是:'+ str(reason))
出错了TAT
错误原因是:invalid literal for int() with base 10: 'abc'
try-finally
try:
f = open('我是一个不存在的文档.txt')
print(f.read())
sum=1+'1'
except:
print('出错啦')
finally:
f.close()
出错啦
Traceback (most recent call last):
File "D:/作业/大一下/暑期/1/Python/Try-Finally.py", line 8, in <module>
f.close()
NameError: name 'f' is not defined
Raise语句
raise ZeroDivisionError
Traceback (most recent call last):
File "D:/作业/大一下/暑期/1/Python/Raise.py", line 1, in <module>
raise ZeroDivisionError
ZeroDivisionError
raise ZeroDivisionError("除数不能为0!")
Traceback (most recent call last):
File "D:/作业/大一下/暑期/1/Python/Raise.py", line 1, in <module>
raise ZeroDivisionError("除数不能为0!")
ZeroDivisionError: 除数不能为0!
for-else
def showMaxFactor(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('请输入一个数:'))
showMaxFactor(num)
请输入一个数:52
52最大的约数是26