在 Python 3 中为函数分配变量名

Assigning a variable name to a function in Python 3

所以我正在编写一个程序,一旦完成,将让用户掷 2 个骰子,然后保留显示的值的 运行 总和,并为掷出的值分配一些点,但是刚开始时,我 运行 遇到了一个问题。 这是我目前所拥有的:

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

(之后,我打算像 diceTwo + diceOne 那样进行计算,然后做所有其他的事情——我知道这很粗糙)

但是当它运行时,它并没有像预期的那样给出漂亮的整数值,它 returns function diceOne at 0x105605730> and a <function diceTwo at 0x100562e18> 有谁知道如何解决这个问题,同时仍然能够分配变量名称以便以后能够执行计算?

您必须 return 函数中的某些内容才能对函数本身之外的任何事物产生影响。然后,在您的函数 greeting() 中,您必须通过调用 diceOne() 而不是 diceOne.

call 函数

尝试:

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

def diceTwo():
    import random
    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':
        diceOne()
        diceTwo()
        print('you have rolled a: ' , diceOne(), 'and a' , diceTwo())

greeting()

您的代码有几个问题。我将post作为答案,因为它比评论更易读

  1. 只导入随机一次,而不是在所有方法中
  2. diceOne() 和 diceTwo() 做同样的事情,所以只定义一个方法 dice()
  3. return 来自 dice() 的值,而不是将 dice() 分配给 random.randint()
  4. 你可以直接在打印语句中调用dice()

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