1.while循环语句:
1 count = 0 2 while count <= 100: 3 print("loop ", count) 4 count += 1 5 print(‘----loop is ended----‘)
2.打印偶数:
1 # 打印偶数 2 # count = 0 3 # 4 # while count <= 100: 5 # 6 # if count % 2 == 0: #偶数 7 # print("loop ", count) 8 # 9 # count += 1 10 # 11 # 12 # print(‘----loop is ended----‘)
3.第50次不打印,第60-80打印对应值 的平方
1 count = 0 2 3 while count <= 100: 4 5 if count == 50: 6 pass #就是过。。 7 8 elif count >= 60 and count <= 80: 9 print(count*count) 10 11 else: 12 print(‘loop ‘, count) count+=1
4.死循环
1 count = 0 2 3 while True: 4 print("forever 21 ",count) 5 count += 1
5.循环终止语句:break&continue
break:用于完全结束一个循环,跳出循环体执行循环后面的语句
continue:不会跳出整个循环,终止本次循环,接着执行下次循环,break终止整个循环
1 # break 循环 2 # count=0 3 # while count<=100: 4 # print(‘loop‘,count) 5 # if count==5: 6 # break 7 # count+=1 8 # print(‘-----out of while loop---‘)
1 #continue 循环 2 count=0 3 while count<=100: 4 print(‘loop‘,count) 5 if count==5: 6 continue 7 count+=1 8 # print(‘-----out of while loop---‘) #一直打印5 9 #continue 跳出本次循环,不会执行count+=1,count一直为5
例1:让用户猜年龄
1 age = 26 2 user_guess = int(input("your guess:")) 3 if user_guess == age : 4 print("恭喜你答对了,可以抱得傻姑娘回家!") 5 elif user_guess < age : 6 print("try bigger") 7 else : 8 print("try smaller")
例2:用户猜年龄升级版,让用户猜年龄,最多猜3次,中间猜对退出循环
1 count = 0 2 age = 26 3 4 while count < 3: 5 6 user_guess = int(input("your guess:")) 7 if user_guess == age : 8 print("恭喜你答对了,可以抱得傻姑娘回家!") 9 break 10 elif user_guess < age : 11 print("try bigger") 12 else : 13 print("try smaller") 14 15 count += 1
例3:用户猜年龄继续升级,让用户猜年龄,猜3次,如果用户3次都错,询问用户是否还想玩,如果为y,则继续猜3次,以此往复【注解提示:相当于在count=3的时候询问用户,如果还想玩,等于把count变为0再从头跑一遍】
count = 0 age = 26 while count < 3: user_guess = int(input("your guess:")) if user_guess == age : print("恭喜你答对了,可以抱得傻姑娘回家!") break elif user_guess < age : print("try bigger") else : print("try smaller") count += 1 if count == 3: choice = input("你个笨蛋,没猜对,还想继续么?(y|Y)") if choice == ‘y‘ or choice == ‘Y‘: count = 0
6.while&else:while 后面的else的作用是,当while循环正常执行完,中间没有被break中止的话,就会执行else后的语句【else 检测你的循环过程有没有中止过(当你的循环代码比较长的时候)】
1 count=0 2 # while count <=5: 3 # count+=1 4 # print(‘loop‘,count) 5 # 6 # else: 7 # print(‘循环正常执行完啦‘) 8 # print(‘-----out of while loop----‘)
1 count=0 2 while count<=5: 3 print(‘loop‘,count) 4 if count==3: 5 break 6 count+=1 7 else: 8 print(‘loop is done‘)
原文地址:https://www.cnblogs.com/xwxs/p/9193632.html
时间: 2024-10-16 06:49:08