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

6. 帐号密码判断

ACCOUNT = 'yancy'
PASSWD = '123!'

count = 0

while count < 1:
    account = input('Enter your account: ')
    passwd = input('Enter your password: ')

    if account == ACCOUNT and passwd == PASSWD:
        print('Welcome to the sso system!')
        break
    elif account == ACCOUNT and passwd != PASSWD:
        print('Your password is wrong!')
    elif account != ACCOUNT:
        print("Your account doesn't exist!")
    count += 1

    if count == 1:
        while True:
            choice = input('Whether not continue?(Y/N): ')
            if choice == 'Y' or choice == 'y':
                count = 0
                break
            elif choice == 'N' or choice == 'n':
                print('You quit the program!')
                break
            else:
                print("You must enter 'Y/y' or 'N/n'!")
                continue

 

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中断跳出

posted @ 2017-11-08 18:07  yancy.lu  阅读(853)  评论(0编辑  收藏  举报