我使用 return 關鍵字來結束函式,并確保變數 (randnum1) 處于正確的范圍內,但 Pylance 表示該變數仍未定義。我該如何解決?(下面的代碼)
def genrand1():
randnum1 = random.randrange(rand1a, rand1b)
return randnum1
rand1prompt = input("The random number will be " randnum1 ". Is this okay? (Type yes or no")
if rand1prompt := "yes":
print("Okay, the number's set.")
num1 = randnum1
elif rand1prompt := "no":
print("Okay. Generating a new random number...")
genrand1()
else:
print("Whoops. Something went wrong. Please type yes or no.")```
uj5u.com熱心網友回復:
您的randnum1輸入陳述句中的 未定義,因為它尚未在全域范圍內定義。randnum1是一個區域變數,因為它只在函式中定義,genrand1()因此只能在genrand1()函式中訪問。
要randnum1全域定義,請將函式的回傳值存盤在其中:randnum1 = genrand1(). 喜歡:
def genrand1():
randnum1 = random.randrange(rand1a, rand1b)
return randnum1
randnum1 = genrand1() #Stored here
rand1prompt = input("The random number will be " randnum1 ". Is this okay? (Type yes or no")
if rand1prompt := "yes":
print("Okay, the number's set.")
num1 = randnum1
elif rand1prompt := "no":
print("Okay. Generating a new random number...")
genrand1()
else:
print("Whoops. Something went wrong. Please type yes or no.")
uj5u.com熱心網友回復:
您可能想用randnum1's回傳它的函式替換第三行中的 。
我假設您是從一個函式回傳它并在函式外部使用相同的變數。
相反,您可能希望將函式的回傳值存盤在一個變數中,并使用該變數代替 randnum1。
例如: - 如果你想使用 randnum1 之類的東西
randnum1 = function()
用你的函式名替換函式。
這只是我最初的猜測,查看完整代碼肯定會更有洞察力。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417970.html
標籤:
下一篇:使用索引時SQLite查詢緩慢
