[英]How to exit only if block in python and not the entire program
在這里我想退出if塊,但不想使用sys.exit(),因為它將終止程序。 我最后要執行幾行,因此只想退出if塊。 不能使用break,因為它會標記錯誤“ break out loop”
-編輯-在此,我希望程序在“ if(retry == 3)”#行55處退出該塊,並在最后打印行。 但是直到使用sys.exit()才完全退出程序,它才發生
import random
import sys
loop = ''
retry = 0
loop = input('Do u want to play lottery ? yes/no : ')
if loop !='yes':
print('Thank you!! visit again.')
sys.exit()
fireball = input('Do you want to play fireball ? yes/no : ')
lotto_numbers = sorted(random.sample(range(0,4),3))
fireball_number = random.randint(0,3)
while loop == 'yes':
user_input1 = int(input('pls enter the first no: '))
user_input2 = int(input('pls enter the second no: '))
user_input3 = int(input('pls enter the third no: '))
print ('your numbers are : ' , user_input1,user_input2,user_input3)
def check():
if lotto_numbers != [user_input1,user_input2,user_input3]:
return False
else:
return True
def fbcheck():
if lotto_numbers == [user_input1,user_input2,fireball_number]:
return True
elif lotto_numbers == [fireball_number, user_input2, user_input3]:
return True
elif lotto_numbers == [user_input1, fireball_number, user_input3]:
return True
else:
return False
retry += 1
result=check()
if (result == True):
print ("Congratulations!! You won!!")
else:
print ("Oops!! you lost.")
if (fireball == 'yes'):
fb_result=fbcheck()
if (fb_result == True):
print ("Congratulations, You won fireball!!")
else:
print ("Sorry you lost fireball.")
print ('No of retries remaining : ' , (3 - retry))
if (retry == 3):
sys.exit()
loop=input('Do you want to try again? yes/no : ')
continue
else:
pass
print ("Winning combo : ",lotto_numbers)
if (fireball == 'yes'):
print ('fireball no : ' , fireball_number)
print('Thank you!! visit again.')
您根本不需要任何東西。 if
塊內部的代碼將執行,腳本將在if
塊之后運行代碼。
簡單地回答您的問題並不會真正幫助您。.因此,讓我首先添加此鏈接 ,您可以在其中使用應用程序高效地學習python。
if
雖如此,請注意, if
不是循環,那么它就不會重復了,繼續編寫代碼只記得停止縮進即可,僅此而已。
即:
if some_condition:
# do stuff
# stop indent and do some more stuff
希望這會有所幫助。
我想我很想你。
您是否要在執行if條件后執行某些操作? 因此,創建一個子任務,然后調用它!
def finish_program():
print("something")
a = "foo"
print("finish program")
loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
print('Thank you!! visit again.')
finish_program()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.