1.1、使用while循环输出1 2 3 4 5 6 7 8 9 10
1 count = 1 2 while count <= 10: 3 print(count) 4 count += 1
1.2、使用while循环输出1 2 3 4 5 6 8 9 10
1 count = 1 2 while count <= 10: 3 if count == 7: 4 print(" ") 5 else: 6 print(count) 7 count += 1
1.3、使用while循环输出1 2 3 4 5 6 8 9 10
1 count = 0 2 while count < 10: 3 count += 1 4 if count == 7: 5 continue 6 else: 7 print(count)
若是把count += 1放在最后一行,当count=7时执行continue,直接跳出去执行下一个循环而不加1,下一个循环进来还是等于7,于是进入死循环,不会再打印6以后的数字。
此外else:也可以不加,因为结果只有两个,不执行continue,肯定就去执行print了。如下
count = 0 while count < 10: count += 1 if count == 7: continue print(count)
也可以用关键词pass,其意思是什么都不执行,直接跳过,亦可以得到相同效果,代码如下:
count = 0 while count < 10: count += 1 if count == 7: pass else: print(count)
2、求1-100所有数之和
a = 1 b = a+1 while b <=100: a = a + b b +=1 print(a)
自己用while循环写的,搜了一下网上的,好像还有很多方法,暂时就接触while,先这样吧。
3、输出1-100内所有的奇数
count = 1 while count <= 100: if count % 2: print(count) count +=1
4、求1-2+3-4+5...+99的所有数的和
sum = 0 count = 1 while count < 100: if count % 2 == 0: sum = sum - count else: sum = sum + count count += 1 print(sum)
5、用户登录(三次机会重试)
i = 0 while i < 3: username = input('请输入用户名:') password = int(input('请输入密码:')) if username == 'CHENooo126' and password == 123456: print('登陆成功') break else: print('登录失败请重新登录') i += 1
2019-03-31