while True
一直循环
age_of_oldboy = 56 while True: guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it.") elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!")
猜对了停止
例1:
age_of_oldboy = 56 while True: guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it.") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!")
例2:只给3次机会猜,猜对了退出
age_of_oldboy = 56 count = 0 while True: if count == 3: break guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it.") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count +=1
while 条件
定义一个变量
while 判断条件(变量的判断)
如果判断条件满足执行的代码
对变量的值进行修改
不可以停止的循环(判断条件一直满足) 称之为死循环
age_of_oldboy = 56 count = 0 while count < 3: guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it.") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count += 1
while 条件 else
i = 0 while i < 5: print(i) if i == 2: break i += 1 else: print("else") #while循环中的break执行 else中的代码将不会执行
age_of_oldboy = 56 count = 0 while count < 3: guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it.") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count +=1 else: print("you have tried too many times...!")
while嵌套
while 条件1:
条件1满足时,做的事情1
条件1满足时,做的事情2
条件1满足时,做的事情3
......
while 条件2:
条件2满足时,做的事情1
条件2满足时,做的事情2
条件2满足时,做的事情3
......
""" * ** *** **** ***** """ # 在默认的情况下 使用print 默认打印完成后 会有一个换行 # print("哈哈") 完整的格式 print("哈哈", end=" ") # 定义一个变量 记录行数 row = 1 while row <= 5: # 定义一个变量 记录列数 col = 1 while col <= row: print("*", end="") col += 1 # 换行 print() row += 1
# 九九乘法表
# 定义一个变量 记录行数 # %2d 显示两位 如果只有一位 使用空格占位 默认为右对齐 # 如果左对齐 就是 %-2d x = 1 while x <= 9: # 定义一个变量 记录列数 y = 1 while y <= x: print("%d * %d = %-2d" % (y, x, x * y), end=" ") y += 1 # 换行 print() x += 1
完