當它要求再次播放第一次并且我輸入 x 時,程式結束。但是如果我繼續玩,并且在第二次,當我輸入 x 時,它并沒有結束。為什么?
def b():
random_number=random.randint(1, 10)
turn=0
score=100
while True:
try :
num=input("Enter a number between 1 and 10 : ")
array.append(num)
turn =1
if int(num)>10 or int(num)<1:
print("Please enter a number within valid range.")
if 1<array.count(num):
print("You have entered this number %s time/s"%array.count(num))
if int(num)==random_number:
print("Excellent you found the number in %s turn/s"%turn)
print("Your score is " str(score))
choice=input("Press enter key to play again or enter x to quit : ")
if choice.lower()=="x":
print("Nice to meet you")
break
else:
b()
score=100
turn=0
elif int(num)>random_number and int(num)>0 and int(num)<11:
print("Go lower")
score-=10
elif int(num)<random_number and int(num)>0 and int(num)<11:
print("Go upper")
score-=10
except ValueError as err:
print("Oh no!, that is not a valid value. Try again...")
uj5u.com熱心網友回復:
您必須在下面的 else 陳述句中添加 break if choice.lower()=="x"。這是因為當您運行函式 b 時,它將啟動另一個 while 回圈,因此有 2 個 while 回圈正在運行。您只是在用戶想要關閉時才中斷,但根據您的代碼結構,當他說他想再次播放時您也應該中斷,因為無論如何都會開始一個新的 while 回圈。這是代碼:
def b():
random_number=random.randint(1, 10)
turn=0
score=100
while True:
try :
num=input("Enter a number between 1 and 10 : ")
array.append(num)
turn =1
if int(num)>10 or int(num)<1:
print("Please enter a number within valid range.")
if 1<array.count(num):
print("You have entered this number %s time/s"%array.count(num))
if int(num)==random_number:
print("Excellent you found the number in %s turn/s"%turn)
print("Your score is " str(score))
choice=input("Press enter key to play again or enter x to quit : ")
if choice.lower()=="x":
print("Nice to meet you")
break
else:
b()
score=100
turn=0
break
elif int(num)>random_number and int(num)>0 and int(num)<11:
print("Go lower")
score-=10
elif int(num)<random_number and int(num)>0 and int(num)<11:
print("Go upper")
score-=10
except ValueError as err:
print("Oh no!, that is not a valid value. Try again...")
如果您認為這回答了您的問題,您可以勾選它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504628.html
