使用函数的返回值

时间:2014-03-12 17:24:34

标签: python-3.x return return-value dice

我想知道如何使用函数中的返回值,并将if = number == 12的结果中的值除以if number == 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         

1 个答案:

答案 0 :(得分: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))
    ...