-1

Write a Python program to guess a number between 1 to 9. Go to the editor Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit. Edit:- i want to print a message everytime a wrong number is input. However i am getting that message even if i write the correct number.

target_num = 3
guess_num = ""

while target_num != guess_num:
    guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
    print("wrong guess")

print('Well guessed!')`
S3DEV
  • 8,768
  • 3
  • 31
  • 42
  • first edit code and format it – furas Jan 20 '22 at 20:18
  • The `while` continues execution until the *end* of the block. So even after the correct value is entered, the `print` is still executed then the block exits. – S3DEV Jan 20 '22 at 20:21
  • Does this answer your question? [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) – Tomerikoo Jan 21 '22 at 20:49

1 Answers1

2

You will want to use to break keyword like so:

target_num=3 
while True:
    guess_num = int(input('Guess a number between 1 and 10 until you get it right : ')) 
    if guess_num == target_num:
        break
    print("wrong guess") 
print('Well guessed!')  

Alternatively, if you don't want to use break you could use:

target_num=3 
guess_num=""
while guess_num != target_num:
    guess_num = int(input('Guess a number between 1 and 10 until you get it right : ')) 
    if guess_num != target_num:
        print("wrong guess") 
print('Well guessed!')  
Eli Harold
  • 2,280
  • 1
  • 3
  • 22