我可以创建一个函数来打破python中的while循环吗?

2024-06-16 13:05:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python编写一个程序来模拟抛硬币或掷骰子。硬币和骰子使用while循环让用户可以选择再次滚动或翻转,例如:

def d4():
    d4ing = True
    while d4ing:        
        print(random.randint(1,4))
        done = input("""would you like to roll again?  Type y to roll again,
type d to roll a dice, or type anything else to exit:""")
        if done == "y":
            continue
        elif done == "d":
            break
        else:
            print("thank you for using my coin/dice simulator")
            sys.exit("goodbye")

我遇到的问题是,我想把从done开始的每一行都放到它自己的函数中,我可以把它插入到每个函数中,而不是像这样一次又一次地把整件事打出来。你知道吗

def d4ing():
    d4ing = True
    while d4ing:
        print(random.randint(1,4))
        rerolling()

def rerolling(): 
    done = input("""would you like to roll again? Type y to roll again, type d to roll a dice, or type anything else to exit:""") 
    if done == "y": 
        continue 
    elif done == "d": 
        break else: 
    print("thank you for using my coin/dice simulator")     
    sys.exit("goodbye") 

我收到的错误消息:

SyntaxError: 'continue' not properly in loop

Tags: toyoudeftypeexit硬币diceelse
1条回答
网友
1楼 · 发布于 2024-06-16 13:05:59

breakcontinue必须在其当前作用域的循环中。不能从函数内部中断上述作用域中的循环。下面是引起SyntaxError: 'break' outside loop错误的一般示例。对continue也是如此。你知道吗

def break_up():
    break # This is a syntax error

while True:
    break_up()

尽管如此,这不是问题,因为您可以使函数返回一个值,并在上限中有条件地break。你知道吗

不过,在您的特定示例中,还可以通过将返回值赋给d4ing来返回是否要重新回滚。你知道吗

def d4():
    d4ing = True
    while d4ing:        
        print(random.randint(1,4))
        d4ing = rerolling()

def rerolling():
    done = input("Would you like to roll again?")
    if done == "y":
        return True
    elif done == "d":
        return False
    else:
        print("thank you for using my coin/dice simulator")
        sys.exit("goodbye")

相关问题 更多 >