首页 > 解决方案 > 如何使功能重复?

问题描述

如果答案错误,如何使函数重复,因此程序选择一个新数字。

制作一个while循环

import random, sys

def randomNumber(diceRoll):

    while True:
        print('Pick a number 1 to 6')
        userEntry = int(input())

        if diceRoll == userEntry:
            print('Correct')
            sys.exit()

        if diceRoll != userEntry:
            print('Wrong, try again')
            print('The number generated was ' + str(diceRoll))
            continue

r = random.randint(1, 6)
outcome = randomNumber(r)

如果用户猜错了,我希望程序再次询问用户随机数,但使用新数字。

标签: pythonfunctionrepeat

解决方案


diceRoll如果猜测错误,只需重置。

import random, sys

def randomNumber(diceRoll):

    while True:
        print('Pick a number 1 to 6')
        userEntry = int(input())

        if diceRoll == userEntry:
            print('Correct')
            sys.exit()

        if diceRoll != userEntry:
            print('Wrong, try again')
            print('The number generated was ' + str(diceRoll))
            diceRoll = random.randint(1, 6)
            continue

r = random.randint(1, 6)
outcome = randomNumber(r)

推荐阅读