Python基础题 - 1
1、使用while循环输入 1 2 3 4 5 6 8 9 10
1 count = 0 2 while count <= 9: 3 count += 1 4 if count == 7:continue 5 print(count)
或:
1 # 把7换成空格 2 count = 0 3 while count < 10: 4 count += 1 5 if count == 7: 6 print(' ') 7 else: 8 print(count) 9 # 不输入空格 10 count = 0 11 while count < 10: 12 count += 1 13 if count == 7:continue 14 print(count) 15 # 用pass 16 count = 0 17 while count <= 9: 18 count += 1 19 if count == 7: 20 pass #直接跳过 21 else: 22 print(count)
2、求1-100的所有数的和
1 count = 0 2 sum = 0 3 while count < 100: 4 count += 1 5 sum = sum + count 6 print(sum)
3、输出 1-100 内的所有奇数
1 count = 0 2 while count < 100: 3 count += 1 4 if count % 2 == 0:continue 5 print(count)
或:
# 第一种方法 count = 1 while count < 101: print(count) count += 2 # 第二种方法 count = 1 while count < 101: if count % 2 == 1: print(count) count += 1
4、输出 1-100 内的所有偶数
1 count = 0 2 while count < 100: 3 count += 1 4 if count % 2 == 1:continue 5 print(count)
5、求1-2+3-4+5 ... 99的所有数的和
1 power = 1 2 count = 0 3 sum = 0 4 while count < 99: 5 count += 1 6 power += 1 7 sum = sum + count*((-1)**power) 8 print(sum)
或:
1 count = 1 2 sum = 0 3 while count < 100: 4 if count % 2 == 0: 5 sum -= count 6 else: 7 sum += count 8 count += 1 9 print(sum)
6、用户登陆(三次机会重试)
1 user_name = 'admin' 2 password = 'admin' 3 count = 0 4 while count < 3: 5 count += 1 6 name = input ('请输入用户名:') 7 if name == user_name: 8 pw = input('请输入密码:') 9 if pw == password: 10 print('登陆成功') 11 break 12 else :print('密码错误!') 13 if count == 3:print('登陆超过三次!请明天重试。') 14 else : 15 print('用户名不存在!') 16 if count == 3 :print('登陆超过三次!请明天重试。')
或:
1 i = 0 2 while i <3: 3 username = input('请输入账号:') 4 password = input('请输入密码:') 5 if username == 'admin' and password == 'admin': 6 print('登陆成功') 7 else: 8 print('登录失败,请重新登录') 9 i += 1