5. 条件控制与循环语句
5. 条件控制与循环语句
5.1 条件控制:if
if条件下常用的操作运算符
<: 小于
<=: 小于或等于
>: 大于
>=: 大于或等于
==: 等于,比较两个值是否相等
!=: 不等于
5.1.1 猜年龄:if条件
- 只允许猜3次,3次输入错误退出程序
age_of_he = 25
count = 0
while count < 3:
guess_age = int(input("guess age: "))
if guess_age == age_of_he:
print("yes, you got it! ")
break
elif guess_age > age_of_he:
print("think smaller...")
else:
print("think bigger")
count +=1
- 优化:如果输入错误次数超过3时,问是否需要继续猜测
age_of_he = 25
count = 0
while count < 3:
guess_age = int(input("guess age: "))
if guess_age == age_of_he:
print("yes, you got it!")
break
elif guess_age < age_of_he:
print("think bigger")
else:
print("think smaller")
count +=1
if count == 3:
continue_confirm = input("do you wanna keep guessing...?\neg:yes/no")
if continue_confirm != 'no':
count = 0
else:
break
5.2 for循环
for i in range(3):
guess_age = int(input("guess age: "))
if guess_age == age_of_he:
print("yes, you got it!")
break
elif guess_age < age_of_he:
print("think bigger")
else:
print("think smaller")
else:
print("you have tried too many times...fuck off")
5.3 while循环
count = 0
while True:
print("count:",count)
count = count +1 #count +=1
if count == 100:
break
# 输出:
...
count: 98
count: 99
Process finished with exit code 0
5.3.1 while else循环
- 优化: 最多只允许猜3次,对输入不正确的结果的提示
age_of_he = 25
count = 0
while count < 3:
guess_age = int(input("guess age: "))
if guess_age == age_of_he:
print("yes, you got it! ")
break
elif guess_age > age_of_he:
print("think smaller...")
else:
print("think bigger")
count +=1
else:
print("you have tried too many times... fuck off")
5.4 条件控制与循环语句中常用功能
5.4.1 range()函数
for i in range(5):
print("loop", i)
# 输出:
loop 0
loop 1
loop 2
loop 3
loop 4
步长为2,打印
for i in range(0,10,2):
print("loop",i)
# 输出:
loop 0
loop 2
loop 4
loop 6
loop 8
5.4.2 continue
continue:跳出本次循环到下一次循环
for i in range(5):
if i < 3:
print("loop: ", i)
else:
print("i:", i)
continue
# 输出:
loop: 0
loop: 1
loop: 2
i: 3
i: 4
5.4.3 break
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。
内循环:外循环10次,每外循环一次,内循环6次
for i in range(10):
print("---",i,"---")
for a in range(10):
print(a)
if a > 4:
break
5.4.4 pass
pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句
>>> while True:
... pass
... # 等待键盘 (Ctrl+C)中断