在Python中实现循环所使用的语句也有for循环和while循环,本篇先对while循环进行说明。
Python中while语句的语法(同样注意冒号和缩进的问题):
while condition:
statement
使用while循环完成0到100数字累加:
sum=0
num=1
while num <= 100:
sum = sum + num
num = num + 1
print (sum)
使用while完成无限循环,要退出的话可以使用exit或者break函数,作用和区别与shell是一样的
while True:
content = input("请输入你想说的话:")
if content == "q":
exit(0)
print (content)
相比shell而言,Python还可以实现while...else...的语法,当while的条件不为真时(比如触发break条件),执行else后面的语句,不过这种用法不会太多,仅需了解。
下面是一个猜年龄的小游戏,就用到了while循环以及whlie...else...语法:
age = 30
count = 0
while count < 5: #如果要永远为真,可以写为while True:
input_age=int(input("please guess my age:"))
if input_age == age:
print ("you are smart")
break
elif input_age > age:
print ("think smaller")
else:
print ("think bigger")
count +=1
else:
print ("you have tried too many times")