Day1:循环语句(While,For)

Posted 中华酷联

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)

  

 

以上是关于Day1:循环语句(While,For)的主要内容,如果未能解决你的问题,请参考以下文章

day1: 变量,多行打印,for循环,while循环,break

python中的while循环与for循环怎么样那个比较好用?

小白的Python之路 day1 表达式if ... else ,while循环,for循环

Day1--var_if_for_while

第六篇:循环语句 - while和for

循环语句 while,do while ,for 循环