Python中while循环用于在满足特定条件的情况下重复执行代码块。只要条件为True,循环就会继续执行。其基本形式:
while 判断条件(condition): 执行语句(statements)……
实例一:计数器控制的while循环
[root@Shell-Python py]# cat while01.py
count = 0
while count < 5:
print(count)
count +=1
# 无限循环(需要谨慎使用)
# while True:
# print("无限循环")
# 使用break语句提前退出循环
输出结果:
[root@Shell-Python py]# python while01.py
0
1
2
3
4
实例二:while循环嵌套if判断语句
[root@Shell-Python py]# cat while02.py
while True:
user_input = input("请输入一个数字:")
print("您输入的数字是:", user_input)
if user_input == '66':
break
print("程序退出了...")
输出结果:
[root@Shell-Python py]# python while02.py
请输入一个数字:12
您输入的数字是: 12
请输入一个数字:66
您输入的数字是: 66
程序退出了..