有一种循环叫死循环,一经触发,就运行个天荒地老、海枯石烂。
count = 0while True: print("count:",count) count +=1 #count = count + 1
while死循环猜年龄
#!/usr/bin/env python# -*- coding:utf-8 -*-#判断age_of_sd是否等于31,如果等于直接跳出循环,如果连续输错3次也会跳出循环。age_of_sd = 31count = 0while True: if count == 3 : break #跳出循环 guess_age = int(input("guess age:")) if guess_age == age_of_sd: print("Yes,you got it") break elif guess_age > age_of_sd: print("Think smaller..") else: print("Think bigger..") count += 1
while死循环猜年龄优化版
#!/usr/bin/env python# -*- coding:utf-8 -*-age_of_sd = 31 #首先定义一个固定的变量值用于比较count = 0 #定义循环次数,初始为0while count < 3: #当count 小于 3的时候循环开始,否则停止循环 guess_age = int(input("guess age of :")) #以数字整形方式输入内容 if guess_age == age_of_sd: #如果输入内容等于之前定义的变量值,则跳出循环 print("Yes,you got it !") break elif guess_age > age_of_sd: #如果输入的内容大于之前定义的变量值,则循环继续 print("Try smaller...") else: #如果输入的内容小于之前定义的变量值,则循环继续 print("Try bigger!") count += 1#if count == 3: #当循环到第三次结束的时候,打印定义好的内容else: #此处的else 相当于上面的 if count == 3 print("Try too many")
while用户自定义循环次数
#!/usr/bin/env python# -*- coding:utf-8 -*-#判断age_of_sd是否等于31,如果等于直接跳出循环,如果连续输错3次也会跳出循环.age_of_sd = 31 count = 0while count < 3 : guess_age = int(input("guess age:")) if guess_age == age_of_sd: print("Yes,you got it") break elif guess_age > age_of_sd: print("Think smaller..") else: print("Think bigger..") count += 1#如果上面的while count < 3不成立,则执行第二次判断,是否继续执行循环, # 如果输入n,则跳出循环,如果输入其他,则循环继续。 if count == 3 : countine_confirm = input("Do you wang to keep guessing? ") if countine_confirm != 'n': count = 0