-
使用while循环输出1 2 3 4 5 6 8 9 10
count = 1 while count < 11: if count == 7: count += 1 continue else: print(count) count += 1
-
求1-100的所有数的和
sum1 = 0 count = 1 while count < 101: sum1 = sum1 + count count += 1 print(sum1) #5050
-
输出 1-100 内的所有奇数
n = 1
sum1 = 0
while n <= 50:
count = 2 * n - 1
sum1 += count
n += 1
print(sum1) #2500
-
输出 1-100 内的所有偶数
n = 1 sum1 = 0 while n <= 50: count = 2 * n sum1 += count n += 1 print(sum1) #2550
-
求1-2+3-4+5 ... 99的所有数的和
n = 1 sum1 = 0 while n < 50: count0 = 2 * n - 1 count1 = 2 * n sum0 = count0 - count1 sum1 += sum0 n += 1 print(sum1)
-
用户登陆(三次机会重试)
username = 'egon'
password = '123'
count = 0
while True:
if count == 3:
print('输错三次,用户锁定!')
break
user_name = input('请输入用户名:').strip()
user_pwd = input('请输入密码:').strip()
if username == user_name and user_pwd == password:
print('登录成功!')
break
else:
print('用户名或密码错误!')
count += 1
7:猜年龄游戏
要求:
允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
egon_age = '18'
count = 0
while True:
if count == 3:
break
inp_age = input('请输入猜测年龄:').strip()
if inp_age == egon_age:
print('恭喜你猜对了!')
break
else:
print('猜错啦')
count += 1
8:猜年龄游戏升级版(选做题)
要求:
允许用户最多尝试3次
每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
如何猜对了,就直接退出
egon_age = '18'
count = 0
while True:
if count == 3:
info = input('请文是否还想继续猜呢(y or n):').strip()
info = info.lower()
if info == 'n':
break
elif info != 'n' and info != 'y':
print('请输入正确的的字母!')
continue
else:
count = 0
inp_age = input('请输入猜测年龄:').strip()
if inp_age == egon_age:
print('恭喜你猜对了!')
break
else:
print('猜错啦')
count += 1