Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何让代码重复?巨蟒骰子_Python_Simulator_Dice - Fatal编程技术网

Python 如何让代码重复?巨蟒骰子

Python 如何让代码重复?巨蟒骰子,python,simulator,dice,Python,Simulator,Dice,我试图找到一种方法让我的程序重复,例如,我希望用户能够选择骰子边4,得到结果,然后选择骰子边12,而不必重新启动代码。我被告知要使用while循环,但我不确定如何做到这一点。请帮助我编写一些代码,这意味着我的程序可以重复多次 此外,我还希望我的程序询问用户是否希望再次滚动,如果输入“是”,请再次选择骰子侧,如果输入“否”,则输出“再见” import random dice = raw_input("Choose a dice size from the following: 4, 6, 12

我试图找到一种方法让我的程序重复,例如,我希望用户能够选择骰子边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"

将该代码段放入函数中

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))

您认为可以在哪里找到有关在Python中使用while循环的信息?提示:从这里开始: