While和for:
while 循环和for循环区别:while可以死循环,for是有边界的
while 循环 | 在给定的判断条件为 true 时执行循环体,否则退出循环体。 |
for 循环 | 重复执行语句 |
嵌套循环 | 你可以在while循环体中嵌套for循环 |
控制语句 | 描述 |
---|---|
break 语句 | 在语句块执行过程中终止循环,并且跳出整个循环 |
continue 语句 | 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。 |
pass 语句 | pass是空语句,是为了保持程序结构的完整性。 |
exit(0):无错误退出
exit(1):有错误退出
退出代码是告诉解释器的(或操作系统)
**可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。
while循环猜年龄游戏:
代码1 错误
# age_of_ycl = 23
# count = 0
# if count < 3 :
# num = 0
# while num < 3 :
# age = int( input("请输入猜测年龄:") )
# if age == age_of_ycl:
# print("666")
# break
# elif age < age_of_ycl:
# print("trybigger")
# else:
# print("trysmaller")
# num += 1
# count += 1
# else:
# reply = input("是否继续猜测?Y or N")
# if reply == 'Y':
# count = 0
# while count < 3:
# age = int(input("请输入猜测年龄:"))
# if age == age_of_ycl:
# print("666")
# break
# elif age < age_of_ycl:
# print("trybigger")
# else:
# print("trysmaller")
# else:
# continue
# print("--------------end-------------")
代码2:自己想的
# age_of_ycl = 23
# while True:
# count = 0
# while count < 3:
# age = int(input("请输入猜测年龄:"))
# if age == age_of_ycl:
# print("666")
# break
# elif age < age_of_ycl:
# print("trybigger")
# else:
# print("trysmaller")
# count += 1
# print("-----end------")
# reply = input("是否继续猜测?Y or N")
# if reply == 'Y':
# continue
# else:
# break
代码3
age_of_ycl = 23
count = 0
while count < 3:
age = int(input("请输入猜测年龄:"))
if age == age_of_ycl:
print("666")
break
elif age< age_of_ycl:
print("try bigger")
else:
print("try smaller")
count += 1
if count == 3:
reply = input("是否继续猜测?Y or N")
if reply == 'Y':
count = 0
else:
break
While …. else 判断 while语句是否 break
for ... else
for循环:
1、for i in range(10):
print("loop:",i )
2、for i in range(10):
if i<5:
continue #不往下走了,直接进入下一次loop
print("loop:",i )
3、for i in range(10):
if i>5:
break #不往下走了,直接跳出整个loop
print("loop:",i )4、
for i in range(1,10,2):---->括号里表达从1到10每间隔2数字打印出来:1 3 5 7 9 print(i)