Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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 2.7)_Python_Python 2.7 - Fatal编程技术网

如何使函数重新启动取决于答案(Python 2.7)

如何使函数重新启动取决于答案(Python 2.7),python,python-2.7,Python,Python 2.7,问题在于我将continue放在何处,如何使其重新启动取决于答案如果希望它一直运行到特定情况,可以将其放在while true循环中。当使用break和continue时,它位于循环上下文中。它可以是for循环或任何类型的循环,但是如果希望循环永远运行(或直到打破它),则可以使用while true 像这样: from random import randint def roll_the_dice(): dice = randint(1, 6) dice2 = randint(1

问题在于我将continue放在何处,如何使其重新启动取决于答案

如果希望它一直运行到特定情况,可以将其放在while true循环中。当使用break和continue时,它位于循环上下文中。它可以是for循环或任何类型的循环,但是如果希望循环永远运行(或直到打破它),则可以使用while true

像这样:

from random import randint
def roll_the_dice():
    dice = randint(1, 6)
    dice2 = randint(1, 6)
    print dice , dice2
    x = raw_input('If you want to reroll press 1 if not press 2:\n')
    if x == int(1):
        continue
    elif x == int(2):
        break
    else:
        print 'Invalid input'

roll_the_dice()

使用
循环
break
continue
没有循环没有多大意义您可以调用roll\u the_dice()而不是continue。可能是重复的我现在尝试了它,它不起作用,我认为您不能使用您在其中定义的函数。您最好使用while循环。像这样使用递归进行输入验证是一种技巧。你能放一个例子吗?增加了一个例子,但请注意它会在无效输入上重新滚动。
from random import randint

def roll_the_dice():
    while True:
        dice = randint(1, 6)
        dice2 = randint(1, 6)
        print dice , dice2
        x = raw_input('If you want to reroll press 1 if not press 2:\n')
        if x == int(1):
            continue
        elif x == int(2):
            break
        else:
            print 'Invalid input'

roll_the_dice()