Python基础【第四周】:异常处理、循环、随机

一.异常处理

案例说明:

 

 

 解决:

try:{语句块1}

except{语句块2}

 1 #demo1.py
 2 #异常处理
 3 answer = 99
 4 while True:
 5     try:
 6         user = eval(input("please input a number:"))
 7         if user == answer:
 8             print("you are right")
 9             break
10         else:
11             print("you miss it")
12     except:
13             print("please input a suitable number:")

输出:

1 please input a number:77
2 you miss it
3 please input a number:kobe
4 please input a suitable number:
5 please input a number:99
6 you are right

注:try except 只是处理异常时使用,try:{语句1},语句1就是可能会出现异常的语句,except:{语句2},语句2就是出现异常的处理。这是最常用的方法,下面还有两个

first:

 

 

second:

 

 

 代码:

 1 answer = 99
 2 while True:
 3     try:
 4         user = eval(input("please input a number:"))
 5         if user == answer:
 6             print("you are right")
 7             break
 8         else:
 9             print("please input again")
10     except:
11         print("Exist Exception")
12     else:
13         print("No Exception")
14     finally:
15         print("I will output anytime")

输出:

please input a number:7
please input again
No Exception
I will output anytime
please input a number:yh
Exist Exception
I will output anytime
please input a number:99
you are right

注:上述程序有点问题,为什么输入99时,程序else:print("No Exception")为什么不输出?按道理来说,for 、while、try:{语句1},后面加else:{语句2},是当{语句1}没问题时才运行{语句2},这里为什么不执行?

关于else的用法可见:https://blog.csdn.net/py_tester/article/details/78336226

 关于随机库random的用法可见:https://www.cnblogs.com/dadahuan/articles/9464038.html

 

posted @ 2020-05-24 16:00  焕熊  阅读(116)  评论(0编辑  收藏  举报