Table of contents
1. Syntax of while loop
"""语法"""
while 判断条件:
ps: This is just a brief introduction to the relevant syntax of the while loop.
ps: The for loop is for each element in the collection, and the while is for judging that the condition is met, then loop until the end condition is met.
2. Application of while loop
num = 0
while num <= 5:
print(num)
num+=1 #给一个跳出循环的条件,否则会一直死循环
3. Supplement the input() function
3.1 Enter the number, then perform mandatory type conversion
ps:input输入的类型是字符串str
num=input("请输入一个数:")#input输入的是一个字符串str
num = int(num) #str和int不能判断,因此用int()强制转换为int型
while num < 10: #如果判断字符串(不是数字)就不需要用int()进行强制转换
print(f"{
num}:小于10")
break #跳出循环
3.2 Input string
num=input("请输入你喜欢的车:")#input输入一个字符串str
while num == 'bmw':
print(f"你喜欢的车是:{
num}")
break #跳出循环
4. Jump out of the loop - break and continue
break
: Jump out of the loop
continue
: skip the following part of the code (do not run the code after continue), return to the beginning of the loop
Five.tips—while loop tips
When there are multiple values that need to be judged, or when there is a condition for executing a statement, a flag (flag) can be set.
flag = True
while flag:
name = input("请输入你的名字:")
if name == 'mayahei':
flag = False
elif name == 'hh':
flag = False
print(f"你的名字是:{
name}")