码迷,mamicode.com
首页 > 其他好文 > 详细

Study 7 —— while循环中止语句

时间:2017-11-08 20:07:52      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:put   nbsp   logs   arp   use   无限   跳出循环   user   完全   

循环的终止语句
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循环中止语句

标签:put   nbsp   logs   arp   use   无限   跳出循环   user   完全   

原文地址:http://www.cnblogs.com/vurtne-lu/p/7805442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!