循環的終止語句
break #用於徹底結束一個循環,跳出循環體執行循環後面的語句
continue #只終止本次循環,接着執行後面的循環oop
1. 打印0-100,截止到第6次ui
count = 0
while count <= 100:
print('Value: ', count)
if count == 5:
break
count += 1
2. 打印0-100,截止到第6次,第6次無限循環打印spa
count = 0
while count <= 100:
print('Value: ', count)
if count == 5:
continue
count += 1
3. 打印1-5,95-101blog
count = 0
while count <= 100:
count += 1
if count > 5 and count < 95:
continue
print('Value: ', count)
4. 猜年齡,容許用戶猜三次,中間猜對跳出循環input
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則結束it
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. 賬號密碼判斷class
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後面的語句sso
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中斷跳出語法