2017-10-13 56 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

沒關係,你是對的。它搞砸了。謝謝,我沒有注意到。 –

相關問題