while循环

1 while 条件:
2     # 要执行的循环体
3  
4 # 如果条件为真,那么循环体则执行
5 # 如果条件为假,那么循环体不执行

死循环

1 count = 0
2 while True:# 条件永远为真
3     print("你是傻子,我知道。。。",count)
4     count += 1

循环中止

1 # break:终止循环
2 
3 # continue:退出当前循环,继续下次循环

while···else···

1 while 条件:
2     # 要执行的循环体
3 else:
4     # 当while循环正常执行完,中间没有被break的话,就会执行else后面的语句

练习题

1、使用while循环输入1 2 3 4 5 6  8 9 10

1 n = 1
2 while n < 11:
3     if n == 7:
4         pass
5     else:
6         print(n)
7     n += 1
8 print("---The end---")

2、求1-100的所有数的和

1 n = 1
2 s = 0
3 while n < 101:
4     s = s + n
5     n += 1
6 print(s)
7 print("---The end---")

3、输出1-100内的所有奇数

1 n = 1
2 while n < 101:
3     if n % 2 == 0:
4         pass
5     else:
6         print(n)
7     n += 1
8 print("---The end---")

4、输出1-100内的所有偶数

1 n = 1
2 while n < 101:
3     if n % 2 != 0:
4         pass
5     else:
6         print(n)
7     n += 1
8 print("---The end---")

5、求1-2+3-4+5···99的所有数的总和

 1 n = 1
 2 s = 0
 3 while n < 100:
 4     if n % 2 == 0:
 5         s = s - n
 6     else:
 7         s = s + n
 8     n += 1
 9 print(s)
10 print("---The end---")

6、用户登录(三次机会)

 1 count = 0
 2 while count<3:
 3     name = input("请输入用户名:")
 4     password = input("请输入密码:")
 5     if name == "admin" and password == "123456":
 6         print("恭喜您,登陆成功!")
 7         break
 8     else:
 9         # print("用户名或密码错误!")
10         print("用户名或密码错误!请重新输入")
11     count +=1
12 if count>=3:
13     print("3次输入错误,您已无法登陆!")
14 print("---The end---")

 

 

 




posted on 2018-03-13 18:50  &&||!  阅读(145)  评论(0编辑  收藏  举报