简体   繁体   中英

Python - How to pass a variable from one method to another in Python?

I've looked around for a question like this. I've seen similar questions, but nothing that really helped me out. I'm trying to pass the choice variable from the method rollDice() to the method main(). This is what I've got so far:

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

I know that I may have other things in here that are redundant or I may have to fix, but I'm just working on this one issue right now. I'm not sure how to pass the choice variable into the main() method. I've tried putting choice == rollDice() in the main() method but that didn't work. I do mostly SQL work, but wanted to start learning Python and I found a website that has 5 beginner tasks but virtually no instructions. This is task one.

You need to put the return value of the function into a variable to be able to evaluate it (I also corrected a few bugs in your code, mainly typos):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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