Day1:循环语句(While,For)

一、while循环

  while 条件:

    条件为真执行的语句

  esle:

    条件为假执行的语句

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
count = 0
while count < 100:
    print("Count:",count)
    count += 1

  猜年龄升级版

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:Hiuhung Wan
 4 age_of_MrWang = 48
 5 count = 0
 6 while count < 3:
 7     guess_age = int(input("Enter the age of Mr Wang:"))
 8     if guess_age == age_of_MrWang:
 9         print("Yes,you got it!")
10         break
11     elif guess_age < age_of_MrWang:
12         print("Think bigger!")
13     else:
14         print("Think smaller!")
15     count += 1
16     # if count == 3:
17     #     print("You have tried too many times...Fuck off!")
18 else:
19     print("You have tried too many times...Fuck off!")
View Code

二、For循环

  for i in range (xx):

    语句

  else:

    上面循环里的语句正常走完了后,才执行这里的语句

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(10):
    print("loop",i)

  再次优化一下猜年龄小程序

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:Hiuhung Wan
 4 age_of_MrWang = 48
 5 for i in range (3):
 6     guess_age = int(input("Enter the age of Mr Wang:"))
 7     if guess_age == age_of_MrWang:
 8         print("Yes,you got it!")
 9         break
10     elif guess_age < age_of_MrWang:
11         print("Think bigger!")
12     else:
13         print("Think smaller!")
14 else:
15     print("You have tried too many times...Fuck off!")
View Code

三、for循环步长问题

  range里可以设置,默认是1

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(0,10,2):   #步长是2
    print("loop",i)

四、猜年龄小程序加入继续玩模式

  思路:猜了三次还没有猜对,提示是否继续猜,如果按n就退出程序,其他键就继续猜。同时判断输入是否为数字

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
age_of_MrWang = 48
count = 0  #计数器
while count < 3:
    guess_age = input("Enter the age of Mr Wang:")
    if guess_age.isdigit(): #输入了数字
        guess_age = int(guess_age)
        if guess_age == age_of_MrWang:
            print("Yes,you got it!")
            break  #猜对了,退出while循环
        elif guess_age < age_of_MrWang:
            print("Think bigger!")
        else:
            print("Think smaller!")
        count += 1
        if count == 3:
            continue_confirm = input("Do you want to keey guessing?")
            if continue_confirm != "n":
                count = 0  # 计数器清零
    else:
        print("Please enter a number!")

  

五、break与continue

  continue:跳出本次循环(或者说:结束当前循环),继续下一次循环

  break:结束整个循环

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(0,10):
    if i < 5:
        print("loop",i)
    else:
        continue
    print("The variable i loops once")

  

六、for循环嵌套

  注意break的使用

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(10):
    print("-------",i)
    for j in range (10):
        print(j)
        if j > 5:
            break  #结束当前循环(j),继续下一次循环

  

原文地址:https://www.cnblogs.com/hiuhungwan/p/7674801.html