2014-03-12 145 views
0

我想知道如何從函數中使用返回值,並將來自if == 12的結果的值從if == 4中分開。或者我需要爲每個骰子分別製作功能?使用來自函數的返回值

import random 

def dice_roll(number): 
    if number == 12: 
     number = random.randint(1,12) 
     print(number) 
     return number 
    elif number == 6: 
     number = random.randint(1,6) 
     print(number) 
     return number 
    else: 
     number == 4 
     number = random.randint(1,4) 
     print(number) 
     return number 

print("12 sided") 
print("6 sided") 
print("4 sided") 

while True: 
    dice_roll(int(input("Which dice would you like to roll? --> "))) 
    doRepeat=input("Go again? --> ") 
    if doRepeat == "no": 
     break   
+0

什麼是「從如果數== 4將來自所述結果從如果數== 12的值」呢? – Kevin

+0

如何將骰子卷選擇存儲在單獨的變量* first *中? 'choice = int(input(「你想擲哪個骰子? - >」)',然後'roll = dice_roll(選擇)'現在你可以應用你認爲需要的算術。 –

+0

我的意思是我可以返回多個值(請參閱while循環),以後如何才能在我的代碼中使用它們? – user3119844

回答

1

我想您所描述的是這樣的:

rolls = {4: [], 6: [], 12: []} # dictionary to hold rolls 
while True: 
    sides = int(input("Which dice would you like to roll? --> ")) # store sides 
    rolls.get(sides, rolls[4]).append(dice_roll(sides)) # roll and add to dict 
    doRepeat=input("Go again? --> ") 
    if doRepeat == "no": 
     break 

正如我對你剛纔的問題指出,雖然,你可以使整個事情更靈活(不僅僅是4 ,6和12):

def dice_roll(sides): 
    number = random.randint(1, sides) 
    print(number) 
    return number 

rolls = {} 
while True: 
    sides = int(input("Which dice would you like to roll? --> ")) 
    rolls.setdefault(sides, []).append(dice_roll(sides)) 
    ... 
+0

無論它是否正確,OP似乎默認爲'4',所以'rolls.get(roll,roll [4])。append(dice_roll(roll))'會更接近...... –

+0

而在你的更新中 - 而不是'如果雙方不在卷檢查只使用'rolls.setdefault(sides,[])。append(dice_roll(sides))' –

+0

優秀點,謝謝;編輯 – jonrsharpe