import random
given_number = round(float(input("Enter a number;\n")))
loop = True
while loop:
def Possibility(maximum):
count = 0
while count == 0:
x = random.randint(0, maximum)
if x:
print("X is True")
else:
print("X is false")
count = 1
print("Possibility calculated")
answer = input("Do you want to try again? Y/N")
if answer == "N":
loop = False
Possibility(given_number)
當我運行代碼時,即使我輸入 N 來回答作為輸入程式仍然繼續運行任何想法為什么會發生這種情況?
uj5u.com熱心網友回復:
import random
given_number = round(float(input("Enter a number;\n")))
def Possibility(maximum):
count = 0
while count == 0:
x = random.randint(0, maximum)
print(x)
if x:
print("X is True")
return True
else:
print("X is false")
count = 1
print("Possibility calculated")
answer = input("Do you want to try again? Y/N")
if answer == "N":
return False
while Possibility(given_number):
given_number = round(float(input("Enter a number;\n")))
Possibility(given_number)
問題是,函式的可能性是在一個while回圈中,這意味著函式在結束之前不會被執行,它不能,因為結束條件在函式中。這應該可以解決您的問題,使其回圈函式本身而不是定義。要跳出回圈,您將使用 return 函式,這是在這種情況下結束回圈的一種簡單方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523710.html
上一篇:僅在完成后再次運行功能
