Search code examples
pythonpython-3.xrandomvariadic-functionsdice

Assigning a variable name to a function in Python 3


So I'm writing a program that, once finished, will have a user roll 2 dice and then keep a running sum of the values shown and assign some points to the values that are rolled, but I am running into a problem when first getting started. This is what I have so far:

def diceOne():
    import random
    a = 1
    b = 6
    diceOne = (random.randint(a, b))

def diceTwo():
    import random
    a = 1
    b = 6
    diceTwo = (random.randint(a, b))

def greeting():
    option = input('Enter Y if you would like to roll the dice: ')
    if option == 'Y':
        diceOne()
        diceTwo()
        print('you have rolled a: ' , diceOne, 'and a' , diceTwo)



greeting()

(after, I plan to do calculations like diceTwo + diceOne and do all the other stuff - i know this is very rough)

But when it runs, it does not give nice integer values as expect, it returns function diceOne at 0x105605730> and a <function diceTwo at 0x100562e18> Does anyone know how to get around this while still being able to assign variable names in order to later be able to perform calculations?


Solution

  • There are several problems with your code. I'll post this as an answer because it's more readable than a comment

    1. Only import random once, not in every method
    2. diceOne() and diceTwo() do the same thing, so just define one method dice()
    3. return a value from dice(), not assign dice() to random.randint()
    4. You can call dice() directly in your print statement

      import random
      
      def dice():
        a = 1
        b = 6
        return random.randint(a, b)
      
      def greeting():
        option = input('Enter Y if you would like to roll the dice: ')
        if option == 'Y':
          print('you have rolled a ' , dice(), 'and a ', dice())
      
      greeting()