![](/img/trans.png)
[英]How do I get a variable in one function to another function in python?
[英]Python - How do I get the defined variable from one function to another function?
我已將其簡化為:
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
def two_player_word():
print("2")
elif gameinput == "1":
def one_player_word():
print("1")
def hangman():
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman()
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
我之前在 'hang()' 中定義了游戲輸入,它收集用戶輸入等等。 我的問題在'hangman()'中我需要再次游戲輸入來制作變量詞(它是這樣制作的,因此用戶可以在生成隨機詞時制作一個詞(two_player_word)或一個玩家(one_player_word()
如果沒有游戲輸入在 function 中,它可以完美運行,但是在玩家贏或輸之后,我希望它讓用戶決定是否要更改游戲模式,如 main() 所示。
還有更多代碼,但認為僅使用它來嘗試找出問題會更容易。
只需將游戲輸入從hang
hangman
gameinput
參數。
def hang():
while True:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput not in ("1", "2"):
continue
hangman(gameinput)
break
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
有兩個問題會導致您的代碼失敗(縮進除外)。
one/two_player_word
),然后嘗試從 function (未定義)外部調用。 您可以通過在 function hang()
之外定義函數來更改此設置。hangman()
使用 gameinput 變量,但它沒有定義也沒有提供。 您可以通過將其作為參數添加到 function 調用來更改此設置。您調整后的代碼可以像這樣工作:
import time
def one_player_word():
print("1")
def two_player_word():
print("2")
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
two_player_word()
elif gameinput == "1":
one_player_word()
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman(gameoverinput)
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.