Python:Day2 :while循环

一、while循环

1、基本循环

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

2、break

break用于退出所有循环

1
2
3
4
while  True :
     print  "123"
     break
     print  "456"

3、continue

continue用于退出当前循环,继续下一次循环

1
2
3
4
while  True :
     print  "123"
     continue
     print  "456"

 

练习题

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 = n + 1
8 print('End')

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

 
1 n = 1
2 s = 0
3 while n < 101:
4     s = s + n
5     n = n + 1
6 print(s)

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

1 n = 1
2 while n < 101:
3     temp = n % 2
4     if temp == 0:
5         pass
6     else:
7         print(n)
8     n = n + 1
9 print('End')
 

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

1 n = 1
2 while n < 101:
3     temp = n % 2
4     if temp == 0:
5         print(n)
6     else:
7         pass
8     n = n + 1
9 print('End')

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

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

6、用户登陆(三次机会重试)

 
 如果用户名或者密码二者其一不正确,则循环重试,循环次数三次
 
   
 1 #用户登录(三次机会重试)
 2 #如果用户名或者密码二者其一不正确,则循环重试,循环次数三次
 3 import getpass
 4 time = 1
 5 while time:
 6     name = raw_input("The user name is: ")
 7     passwd = getpass.getpass("The password is: ")
 8     if name!="bill" or passwd!="123":
 9         if time < 3: 10 print("Please try again") 11 time += 1 12 continue 13 else: 14 print("Sorry, time is over!") 15 break 16 else: 17 print("Congraulation to you for log in success") 18 break
 
    
   
 1 count = 0
 2 while count < 3 :
 3     user = input('请输入用户名:')
 4     pwd = input('请输入密码:')
 5     if user == 'wyf' and pwd == '123':
 6         print('欢迎登陆')
 7         break
 8     else: 9  print('用户名或者密码错误') 10 count = count +1

猜你喜欢

转载自www.cnblogs.com/Quantum-World/p/10477799.html
今日推荐