1、在循环中使用continue输出1-10之间的奇数
num=0
while num <10:
num += 1
if num %2 == 0: #--%--运算符,相除返回余数
continue
print(num)
2、使用 active = True\False 设置循环标志
#调查用户梦想的度假胜地
responses={}
name=input("What's your name?")
resort=input("What's your dream resort?")
polling_active=True
while polling_active:
responses[name]=resort
repeat=input("Would you like to let another person respond?(yes/no)")
if repeat == 'no':
polling_active = False
print('\n=== Poll Results ===')
for name,resort in responses.items():
print(name+"'s dream resort is %s."%resort)
3、使用break退出循环
prompt='please input some pizza toppings:'
prompt += "\nEnter 'quit' when you are finished."
toppings=''
while toppings != 'quit':
toppings=input(prompt)
if toppings != 'quit':
print("we'll add some "+str(toppings)+" to pizza!")
else:
break
4、避免无限循环
x = 1
while x < 5:
print(x)
x += 1 #此处必不可少
5、while循环与if-else语句结合使用
#while循环求64是2的几次方
a = 64
i = 0
while True:
a /= 2
i += 1
if a == 1:
print(i)
break
else:
continue