Study 7 —— while循环中止语句
Posted yancy.lu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Study 7 —— while循环中止语句相关的知识,希望对你有一定的参考价值。
循环的终止语句
break #用于完全结束一个循环,跳出循环体执行循环后面的语句
continue #只终止本次循环,接着执行后面的循环
1. 打印0-100,截止到第6次
count = 0
while count <= 100:
print(‘Value: ‘, count)
if count == 5:
break
count += 1
2. 打印0-100,截止到第6次,第6次无限循环打印
count = 0
while count <= 100:
print(‘Value: ‘, count)
if count == 5:
continue
count += 1
3. 打印1-5,95-101
count = 0
while count <= 100:
count += 1
if count > 5 and count < 95:
continue
print(‘Value: ‘, count)
4. 猜年龄,允许用户猜三次,中间猜对跳出循环
count = 0
age =18
while count < 3:
user_guess = int(input(‘Input Number: ‘))
if user_guess == age:
print(‘Yes, you are right!‘)
break
elif user_guess > age:
print(‘Try smaller!‘)
else:
print(‘Try bigger!‘)
count += 1
5. 猜年龄,允许用户猜三次,中间猜对跳出循环,猜了三次后若没有猜对,询问是否继续,Y则继续,N则结束
count = 0
age =18
while count < 3:
user_guess = int(input(‘Input Number: ‘))
if user_guess == age:
print(‘Yes, you are right!‘)
break
elif user_guess > age:
print(‘Try smaller!‘)
else:
print(‘Try bigger!‘)
count += 1
if count == 3:
choice = input(‘Whether or not to continue?(Y/N): ‘)
if choice == ‘Y‘ or choice == ‘y‘:
count = 0
elif choice == ‘N‘ or choice == ‘n‘:
pass
else:
print(‘You must input Y/y or N/n !‘)
pass
while ... else语法
当while循环正常执行完毕,中间没有被break中止,就会执行else后面的语句
count = 0
while count <= 100:
print(‘Value: ‘, count)
if count == 5:
break #有break时,else下面的内容就不打印,没有break时,就打印。
count += 1
else:
print(‘loop is done.‘)
else语法可用于判断while程序中间是否被break中断跳出
以上是关于Study 7 —— while循环中止语句的主要内容,如果未能解决你的问题,请参考以下文章