Python基础(练习题)
1、使用while循环输出 1 2 3 4 5 6 8 9 10
1 import time 2 num = 1 3 while True: 4 5 if num == 7: 6 num += 1 7 continue 8 print(num) 9 if num == 10: 10 break 11 num += 1 12 time.sleep(1)
2、求1-100的所有数的和
方法一:
1 start = 1 2 sum = 0 3 while start <= 100: 4 sum = sum + start 5 start += 1 6 print(sum)
方法二:
1 sum = 0 2 start = 1 3 while True: 4 sum = sum + start 5 if start == 100: 6 break 7 start += 1 8 9 print(sum)
3、输出 1-100 内的所有奇数
方法一:
1 start = 1 2 while True: 3 if start % 2 == 1: 4 print(start) 5 start += 1 6 if start == 100: 7 break
方法二:
1 start = 1 2 while start < 101: 3 temp = start % 2 4 if temp == 1: 5 print(start) 6 else: 7 pass 8 start += 1
4、输出 1-100 内的所有偶数
方法一:
1 start = 1 2 while True: 3 if start % 2 == 0: 4 print(start) 5 start += 1 6 if start == 101: 7 break
方法二:
1 start = 1 2 while start < 101: 3 temp = start % 2 4 if temp == 0: 5 print(start) 6 else: 7 pass 8 start += 1
5、求1-2+3-4+5 ... 99的所有数的和
1 sum = 0 2 start = 1 3 while start <100: 4 temp = start % 2 5 if temp == 1: 6 sum = sum + start 7 else: 8 sum = sum - start 9 start += 1 10 11 print(sum)
6、用户登陆(三次机会重试)
1 s = 0 2 while s < 3: 3 hostname = input("请输入用户名:") 4 pwd = input("请输入密码:") 5 if hostname == "wxq" and pwd == "wxq": 6 print("登录成功!") 7 break 8 else: 9 if s == 2: 10 print("用户名密码错误,请重置!") 11 else: 12 print("登录失败请重试!") 13 s += 1