Write a Python program to guess a number between 1 to 9 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.
The above statement is given.. i have written code but it hangs after giving input.. after ctr+c it shows last call on if statement.
from random import randint as rt
g= rt(1,9)
ug= int(input("Guess a number"))
while True:
if g==ug:
print("Well guessed!")
break
else:
continue
Advertisement
Answer
OP:
i have written code but it hangs after giving input.. after ctr+c it shows last call on if statement.
Because:
Imagine you’ve entered an incorrrect number, the condition fails, the loop continues, it checks the same condition and fails again, keeps going on and on.
What you need:
Put the
ug = int(input("Guess a number"))
inside the while loop.Put an
else
block with aIncorrect Guess
prompt message.
Hence:
from random import randint as rt
g= rt(1,9)
while True:
ug = int(input("Guess a number: "))
if g==ug:
print("Well guessed!")
break
else:
print("Incorrect!n")
OUTPUT:
Guess a number: 4
Incorrect!
Guess a number: 5
Incorrect!
Guess a number: 6
Incorrect!
Guess a number: 7
Incorrect!
Guess a number: 8
Well guessed!
Process finished with exit code 0