马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1.丰富的else语句
1)要么怎样,要么不怎样
If...else...
2)干完了能怎样,干不完就别想怎样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)
请输入一个数:25
25最大的约数是5
请输入一个数:11
11是素数!
3)没有问题,那就干吧try:
int('abc')
except ValueError as reason:
print('出错啦:' + str(reason))
else:
print('没有任何异常!')
出错啦:invalid literal for int() with base 10: 'abc'
try:
int('abc')
except ValueError as reason:
print('出错啦:' + str(reason))
else:
print('没有任何异常!')
没有任何异常!
try:
print(int('123'))
except ValueError as reason:
print('出错啦:' + str(reason))
else:
print('没有任何异常!')
123
没有任何异常!
try:
print(int('abc'))
except ValueError as reason:
print('出错啦:' + str(reason))
else:
print('没有任何异常!')
出错啦:invalid literal for int() with base 10: 'abc'
2.简洁的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()
出错啦:not readable
try:
with open('data.txt', 'w') as f:
for each_line in f:
print(each_line)
except OSError as reason:
print('出错啦:' + str(reason))
出错啦:not readable
|