[英]Python - How to pass a variable from one method to another in Python?
我到處尋找這樣的問題。 我見過類似的問題,但沒有什么真正幫助我。 我試圖將選擇變量從方法rollDice()傳遞給方法main()。 到目前為止,這是我得到的:
import random
import os
import sys
def startGame():
answer = input('Do you want to play Super Dice Roll?\nEnter 1 for Yes\nEnter 2 for No\n'
os.system('cls')
if (answer == '1'):
rollDice()
elif(answer == '2'):
print('Thank you for playing!')
else:
print('That isn/t a valid selection.')
StartGame()
def rollDice():
start = input('Press Enter to roll dice.')
os.system('cls')
dice = sum(random.randint(1,6) for x in range (2))
print('you rolled ',dice,'\n')
choice = input('Do you want to play again?\nEnter 1 for Yes\nEnter 2 for No.\n)
return choice
def main():
startGame()
while (choice == '1'):
startGame()
print('Thank you for playing')
print('!~!~!~!~WELCOME TO SUPER DICE ROLL~!~!~!~!~\n')
main()
我知道我在這里可能還有其他多余的事情,或者可能需要修復,但是我現在正在處理這個問題。 我不確定如何將選擇變量傳遞到main()方法中。 我試過將choice == rollDice()放在main()方法中,但這沒用。 我主要從事SQL工作,但想開始學習Python,我發現了一個網站,該網站有5個初學者任務,但實際上沒有說明。 這是任務一。
您需要將函數的返回值放入變量中才能進行評估(我還糾正了代碼中的一些錯誤,主要是錯別字):
import random
import os
def startGame():
answer = input('Do you want to play Super Dice Roll?\nEnter 1 for Yes\nEnter 2 for No\n')
os.system('cls')
while answer == '1':
answer = rollDice()
if answer == '2':
print('Thank you for playing!')
else:
print('That isn/t a valid selection.')
startGame()
def rollDice():
input('Press Enter to roll dice.')
os.system('cls')
dice = sum(random.randint(1,6) for x in range (2))
print('you rolled ', dice, '\n')
choice = input('Do you want to play again?\nEnter 1 for Yes\nEnter 2 for No.\n')
return choice
def main():
print('!~!~!~!~WELCOME TO SUPER DICE ROLL~!~!~!~!~\n')
startGame()
print('Thank you for playing')
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.