如何让我的代码重复? Python骰子

时间:2014-12-01 21:09:54

标签: python simulator dice

我正试图找到一种方法让我的程序重复,所以例如我希望用户能够选择骰子4,得到结果,然后选择骰子12,而不必重新启动代码。我被告知使用while循环,但我不确定如何做到这一点。请帮助编写一些意味着我的程序可以重复多次的东西。

此外,我还希望我的程序询问用户是否要再次滚动,如果输入'是'再次选择骰子方面,如果'否'输出'再见'。

import random

dice = raw_input("Choose a dice size from the following: 4, 6, 12: ")
if dice =="4":            
    print "The result from the 4 sided die is: " ,random.randint(1,4)    
elif dice == "6":    
    print "The result from the 6 sided die is: " ,random.randint(1,6)    
elif dice =="12":    
    print "The result from the 12 sided die is: " ,random.randint(1,12)    
else:    
    print "Invalid die entered, please try again"

1 个答案:

答案 0 :(得分:1)

将该代码段放在函数

import random
def rollDice():
    dice = input("Choose a dice size from the following: 4, 6, 12: ")
    if dice =="4":
        print("The result from the 4 sided die is: " ,random.randint(1,4))
    elif dice == "6":
        print("The result from the 6 sided die is: " ,random.randint(1,6))
    elif dice =="12":
        print("The result from the 12 sided die is: " ,random.randint(1,12))
    else:
        print("Invalid die entered, please try again")

然后你可以在循环中调用该函数

for _ in range(5):
    rollDice()

请注意,您可以更简洁地编写等效函数

def rollDice():
    dice = int(input("Choose a dice size from the following: 4, 6, 12: "))
    if dice not in (4,6,12):
        print("Invalid die entered, please try again")
    else:
        roll = random.randint(1,dice)
        print("The result from the {} sided die is {}".format(dice,roll))