-1

I'm writing a code for a guessing game where the user can choose a range for the number to be in, the program will choose a random number, and the user can guess the number until they are correct.

I've tried using conditionals and a while loop but I cannot get it to run.

if (userGuess > targetNum):

    print "\nToo high\n"

elif (userGuess < targetNum):
        print "\nToo low\n"

else:
        print "\nThat's it! Nice job!\n"

This program runs but I need help getting it to loop so that the user can input their guess and get feedback if it's too high or too low until they guess the correct number. Thanks

Liv
  • 1
  • 1
  • add in `while True:` and then add break statement when condition is satisfied. – vb_rises May 06 '19 at 14:43
  • 5
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – ruohola May 06 '19 at 14:44

3 Answers3

0

You need to ensure that you break the loop when you get to the success case

targetNum = 5
while True:
    userGuess = int(input("Guess Number"))
    if (userGuess > targetNum):
        print("\nToo high\n")
        continue
    elif (userGuess < targetNum):
        print("\nToo low\n")
        continue
    #Break here
    else:
        print("\nThat's it! Nice job!\n")
        break

The output might look like

Guess Number7

Too high

Guess Number9

Too high

Guess Number12

Too high

Guess Number5

That's it! Nice job!
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

add a boolean which will be triggered by the condition

wrong = True

while(wrong) : 
  if (userGuess > targetNum):
      print "\nToo high\n"
  elif (userGuess < targetNum):
      print "\nToo low\n"
  else:
      print "\nThat's it! Nice job!\n"
      wrong = False 
nassim
  • 1,547
  • 1
  • 14
  • 26
0

You should place your IF statements inside a while True: loop.

userGuess = float(input("What's your guess? "))
targetNum = 10

while True:
    if userGuess > targetNum:
        print ("\n Too high\n")
        userGuess = float(input("What's your guess? "))
    elif userGuess < targetNum:
        print ("\n Too low\n")
        userGuess = float(input("What's your guess? "))
    else:
        print ("\n That's it! Nice job! \n")
        break
20r25g22e
  • 97
  • 4