1.使用while循环输出1 2 3 4 5 6 8 9 10
1 count = 1 2 while count < 11: 3 if count == 7: 4 count+=1 5 continue 6 print(count) 7 count+=1
2.求1-100的所有数的和
1 num = 1 2 summing = 0 3 while num < 101: 4 summing+=num 5 num+=1 6 print(summing)
3.输出 1-100 内的所有奇数
1 num = 1 2 while num < 101: 3 if num%2 ==1: 4 print(num) 5 num+=1
4.输出 1-100 内的所有偶数
1 num = 1 2 while num < 101: 3 if num%2 ==0: 4 print(num) 5 num+=1
5.求1-2+3-4+5 ... 99的所有数的和
1 num = 1 2 summing = 0 3 while num <100: 4 if num % 2 ==1: 5 summing+=num 6 else: 7 num = -num 8 summing+=num 9 num =-num 10 num += 1 11 print(summing)
6. 用户登陆(三次机会重试)
1 count = 0 2 while count<3: 3 name = input('请输入你的用户名:') 4 pwd = input('请输入你的密码:') 5 if name == 'egon' and pwd == '123': 6 print('login successful') 7 break 8 else: 9 print('name or passward error') 10 count+=1 11 else : 12 print('尝试次数太多')
7:猜年龄游戏 要求: 允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
1 count = 0 2 tag = True 3 while tag: 4 if count<3: 5 age = input('猜猜看我的年纪:') 6 age = int(age) 7 if age == 25: 8 print('猜对了,恭喜') 9 tag = False 10 else: 11 print('猜错了,请继续') 12 count+=1 13 continue 14 tag = False
8:猜年龄游戏升级版 要求: 允许用户最多尝试3次 每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序 如何猜对了,就直接退出
count = 0 tag = True while tag: if count<3: age = input('猜猜看我的年纪:') age = int(age) if age == 25: print('猜对了,恭喜') tag = False else: print('猜错了,请继续') count+=1 else: while tag: user_inp = input('是否继续猜?Y/N') if user_inp == 'y'or user_inp =='Y': count=0 break elif user_inp=='n'or user_inp=='N': print('谢谢,结束了') tag = False else: print('请按要求输入')
九九乘法表
for i in range(1,10): for j in range(1,i+1): print('%s * %s = %s'%(j,i,i*j),end=' ') print()
结果:
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
#金字塔
1 max_level = 10 2 for i in range(1,max_level+1): 3 print(' '*(max_level-i)+'*'*(2*i-1))