Python—如何在Python中将变量从一个方法传递到另一个方法?

Python—如何在Python中将变量从一个方法传递到另一个方法?,python,function,variables,methods,Python,Function,Variables,Methods,我到处找过这样的问题。我见过类似的问题,但没有什么真正帮助我。我试图将choice变量从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')

我到处找过这样的问题。我见过类似的问题,但没有什么真正帮助我。我试图将choice变量从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()

我知道这里可能有其他多余的东西,或者我可能需要修复,但我现在正在处理这个问题。我不知道如何将choice变量传递到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()

您对rollDice的输入缺少一个“如果这是任务1并且没有instruction@depperm是的,你是对的。代码在另一台机器上,我刚把它打出来,却错过了那部分。然而,我确实包括了这一点。是的,我理解尝试另一个网站。我只是觉得我要做的研究越多,我学到的东西就越多。谢谢你的回答。这就引出了另一个问题:如果我在main中声明choice='1',那么不管用户输入什么,它不会总是以'1'结束吗?如果用户选择不再玩游戏并选择“2”,该怎么办?选择class='1'只是第一次开始游戏的默认值。在choice=startGame中,变量将被实际用户输入覆盖,然后在下次运行while循环时使用。如果您喜欢我的答案,请在投票按钮下方的复选标记处接受,我将不胜感激。谢谢,好的。我试过了,我不得不调试。当我一步一步地运行它时,它很好地跟随,直到我选择“2”作为用户输入。它选择了IF语句的正确路径,然后在打印“感谢您的参与!”它存储了“2”供选择。但随后它返回while循环,检查choice的值,并确定choice等于“1”。我不确定它是否将输入值传递给main。我在想,可能是因为它没有传递值“2”,所以当它返回到main时,它保留了它在“1”中已经知道的选择实例?@AP1:我更新了我的答案。现在,它的工作方式与您预期的一样。以前的结构对于这项任务来说太复杂了。所以我把它简化了很多。