0

How can I make the function repeat if the answer is wrong, so the program chooses a new number.

Making a while loop

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)

I want the program to ask the user the random number again if the user guessed wrong, but with a new number.

Jonas
  • 1,838
  • 4
  • 19
  • 35
  • @TalhaIsrar there's absolutely not need for recursion here... – Jon Clements Jan 20 '19 at 14:08
  • 1
    Seeing as this is in a while-true, recursion will be a bad solution and likely exhaust the call stack. In your function though, it seems you just want to generate the random number **inside the loop** thereby having a fresh random number every iteration. – krato Jan 20 '19 at 14:12
  • the marked duplicate is about something else.. the question is about resetting the guess – Jonas Jan 20 '19 at 14:16

1 Answers1

0

Just reset diceRoll if the guess was wrong.

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)
Jonas
  • 1,838
  • 4
  • 19
  • 35