python while条件和if判断的总练习
输出123456 89的数字
num =1 while num < 11: if num == 7: pass else: print(num) num = num + 1
输出1-100的奇数与偶数
奇数方法
num = 0
while num < 101:
answer = num % 2
if answer == 0:
pass
else:
print(num)
num = num + 1
偶数方法
num = 0
while num < 101:
answer = num % 2
if answer == 0:
print(num)
else:
pass
num = num + 1
1到10相加
n = 1 s = 0 while n < 11: n = n + 1 s = s + n print(s)
算法思路:
s = 0
n = 1
n = n + 1
s =(n + 1 + s) *10次
2 1 + 1 + 0 1
5 2 + 1 + 2 2
9 3 + 1 + 5 3
...
65 10
1-2+3-4+5-6..10所有数的和
'1-2+3-4+5-6+7..10' n = 1 #n就是1-10的数列 s = 0 #s之前数的总和 while n < 11: answer = n % 2 #判断数列是偶数还是奇数 if answer == 0: s = s - n #数列遇到偶数时相减 else: s = s + n #数列遇到奇数时相加 n = n + 1 #产生1-10的数列 print(s) #打印语句块执行过程的和 print(s) #打印总和
算法思路: s = 0 n = 1 奇数 偶数 s = s + n s = s - n
break 跳出循环
num = 0 while num < 11: if num == 7: print("hi") break else: print(num) num = num + 1 print("---and---")
输出:
1
2
...
6
hi
---and---
当num等于7的时候打印的是hi
break跳出循环语句块
continue 继续循环
num = 0 while num < 11: if num == 7: print("hi") continue else: print(num) num = num + 1 print("---and---")
输出:
1
2
...
6
hi
hi
...
当num等于7的时候continue 继续从等于7开始循环
结果打印1到6后面是无限个hi
用户登录测试,3次错误提醒
'登陆3次错误提醒' num = 0 while num < 3: user = input("请输入账号:") passwd = int(input("请输入密码:")) if user == "root" and passwd == 123456: print("登陆成功") break else: print("账户或密码错误") num = num + 1