python学习(4)循环语句

循环语句主要有两个,一个是 while ;一个是for in range()

以案例来说明:

写一个猜数字的游戏,正确的数字等于38。如果数字等于38,则提示正确,然后结束;如果数字大于38则提示大了,小于38则提示小了。

可以猜3次,超过3次则显示尝试次数过多。

先以while写一段代码:

 1 #!/usr/bin/env python
 2 # -*- coding: UTF-8 -*-
 3 # Author:show530
 4 
 5 
 6 right_number=38
 7 count=0  #定义一个函数,初始值为0
 8 while count<3:  #当该函数小于3的时候,执行以下。count用于判断次数。
 9     guess=int(input("Please Guess The Number:"))
10     if guess==right_number:
11         print("great! you are right!".title())
12         break
13     elif guess>right_number:
14         print("more then number!".title())
15     else:
16         print("less then number!".title())
17         count +=1  #count自增计算
18     if count==3: #这段代码把程序做了一些改进,3次之后给玩家一个选择是否继续猜?
19             countinue=input("Do you want keep guessing? (y or n)")
20             if countinue=="y":
21                 count=0
22             if countinue=="n":
23                 print("see you next time!".title())
24 
25 #else:
26     #print("you have trid too much time!".title())

以for in range() 写一段代码。不过for语句暂时没找到方法实现3次之后给玩家继续猜(这块可能需要引入一个函数,回头再认真想想)

2018年9月8日更新程序:其实这个代码很简单,加上一个continue即可解决,在循环语句中,break代表中断循环,往下继续执行代码;continue代表在命令后执行向上循环。

以for range()作为循环的起始条件的语句一般都需要用到continue或break用来控制循环语句。

从编程的角度,用for循环一般比while语句要简练,除非的判断逻辑,否则建议用for来执行循环。

 1 #!/usr/bin/env python
 2 # -*- coding: UTF-8 -*-
 3 # Author:show530
 4 
 5 
 6 right_number=38
 7 for i in range(3):
 8     guess=int(input("Please Guess The Number:"))
 9     if guess==right_number:
10         print("great! you are right!".title())
11         break
12     elif guess>right_number:
13         print("more then number!".title())
14     else:
15         print("less then number!".title())
16         continue
17 
18 else:
19     print("you have trid too much time!".title())
20     
原文地址:https://www.cnblogs.com/show530/p/python.html