繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM