2017-10-13 58 views
-5

因此,我正在编写一个程序,一旦完成,它将有一个用户滚动2个骰子,然后保持所显示值的运行总和,并将一些点分配给值是滚动的,但我第一次开始时遇到问题。 这是我到目前为止有:在Python中为函数赋一个变量名3

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和做所有其他的东西 - 我知道这是很粗糙)

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

+1

创建与函数同名的变量是一种糟糕的编程习惯。 – eyllanesc

+2

因为你正在引用这些函数,而不是它们返回的值(你完全忽略了)。你的两个函数也是相同的,所以*为什么你有两个函数?*你应该更像'rollOne = dice()'和'rollTwo = dice()'。 – jonrsharpe

+1

变量只存在于创建它们的上下文中,在您的情况下,变量只存在于函数内部,所以如果您从函数外部打印diceOne,则会将其视为函数。你的代码对我来说似乎很荒谬。 – eyllanesc

回答

1

有几个问题与您的代码。我会张贴此作为一个答案,因为它比评论

  1. 只导入随机一次更具可读性,而不是在每一个方法
  2. diceOne()和diceTwo()做同样的事情,所以只要定义一个方法dice()
  3. 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() 
    
+0

非常感谢!我明白我现在出错了! – Bro

-1

你必须return东西从你的功能,他们有任何功能本身以外的任何影响。然后,在你的功能greeting()你必须call的功能,通过调用diceOne()而不是diceOne

尝试:

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

从我的文本编辑器直接复制,它工作得很好。 –

+0

没关系,你是对的。它搞砸了。谢谢,我没有注意到。 –

相关问题