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

时间:2017-10-19 15:24:22

标签: python function variables methods

我四处寻找这样的问题。我见过类似的问题,但没有什么能真正帮助我。我正在尝试将方法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()方法。我试过在main()方法中放置choice == rollDice()但是没有用。我主要做SQL工作,但是想开始学习Python,我找到了一个有5个初学者任务但几乎没有说明的网站。这是第一项任务。

1 个答案:

答案 0 :(得分:1)

您需要将函数的返回值放入变量中才能对其进行评估(我还更正了代码中的一些错误,主要是错别字):

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()