我試圖從函式內部呼叫一些值,但
global給了我更多錯誤
def init():
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
Rounds = int(Rounds)
for i in range (Rounds):
None
它不僅僅是一個變數,我需要在函式之后呼叫大約 6 個變數。這里Rounds在for loop是否顯示錯誤說它沒有定義。
uj5u.com熱心網友回復:
問題是Rounds一個區域變數,僅在內部定義init以修復您可以通過以下方式使其成為全域變數
:
def init():
global Rounds
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
Rounds = int(Rounds)
for i in range(Rounds):
None
uj5u.com熱心網友回復:
如果需要訪問全域變數,需要global在他們之前提及
Rounds = None
def init():
global Rounds
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
Rounds = int(Rounds)
init() # call method to populate Rounds
for i in range (Rounds):
None
更安全的方式
def init():
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
Rounds = int(Rounds)
return Rounds
for i in range (init()):
None
uj5u.com熱心網友回復:
不需要使用global,使用global是不好的做法。只需回傳值init:
def init():
rounds = input("enter the amount of rounds: ")
while rounds.isnumeric() == False or int(rounds) <= 0:
rounds = input("enter a valid value: ")
return int(rounds)
Rounds = init()
for i in range(Rounds):
print(i)
uj5u.com熱心網友回復:
除了其他答案之外,將函式中的區域變數設為全域變數并不是一個好主意。事實上,global關鍵字應該盡量少用。在某些情況下,它可能會導致麻煩。您有更好的方法來實作這一目標:
def init():
global Rounds
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
return int(Rounds)
for i in range(init()):
None
或者如果你想在Rounds其他地方使用,試試這個:
def init():
global Rounds
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
return int(Rounds)
# In python 3.8
for i in range(Round := init()):
None
# In python 3.7
Round = init()
for i in range(Round):
None
uj5u.com熱心網友回復:
def init():
global Rounds
Rounds = input("enter the amount of rounds: ")
while Rounds.isnumeric() == False or int(Rounds) <= 0:
Rounds = input("enter a valid value: ")
Rounds_int = int(Rounds)
for i in range(Rounds_int):
pass
您需要添加 global 和 in for i in range (Rounds): None you have space
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/329927.html
