I'm trying to write a code that stops the trial only when it's correct, but if I do it like this, the number of attempts will be infinite, so where should I put the tries=tries+1
import random
tries=0
num=random.randint(1,100)
print("Guess the number between 1 and 100")
g=int (input ("Enter a number")
while True :
tries=tries+1
if g>num:
g=int("Guess a number less than %d: "%g")
elif g<num:
g=int("Guess a number greater than %d: "%g")
else :
print("Congratulations! Number of attempts =",tries)
It's because there's no exit from the while loop when you end the number.
After finding the answer, g == num
is always established, and in that state, tries
plus 1 and tries
are constantly being executed.
If you put break at the end of else
part, it will be solved.
In addition, when using while loop, you often use whileTrue:
first, but if there is a condition where the loop ends, it is better to specify it in the condition of while
rather than using break.
import random
tries=0
num=random.randint(1,100)
print("Guess the number between 1 and 100")
g=int (input ("Enter a number")
while g != num:
tries=tries+1
if g>num:
g=int("Guess a number less than %d: "%g")
elif g<num:
g=int("Guess a number greater than %d: "%g")
else :
print("Congratulations! Number of attempts =",tries)
© 2024 OneMinuteCode. All rights reserved.