5
\$\begingroup\$

The problem is to ask the user to guess a number between 1 to 100 and compare it with a random number of that range. If user guessed number is lesser/greater than the random number print "too low" or "too high" accordingly. Take new input asking the user to guess the correct number again. When the guessed number matches with the random number print "you win" and the number of attempts the user required to guess it.

import random
u_num = int(input("guess a number between 1 to 100: "))
w_num = random.randint(1,100)
i = 1
while u_num != w_num:
    if u_num < w_num:
        print("too low")
    else:
        print("too high")
    u_num = int(input("guess again: "))
    i += 1
print(f"you win, and you guessed this number in {i} times!")
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Your variable names are a little impenetrable - best to use whole words.

Consider adding input validation as a next step to enhancing this program's functionality - what if a user guesses "banana"?

Pythonic code generally discourages the maintenance of your own loop variables (i). I would move your termination condition into the loop body - where you're already checking the guess anyway - and count in your loop declaration.

This example code does the above, minus input validation:

import random
from itertools import count

guess = int(input("Guess a number between 1 to 100: "))
secret = random.randint(1, 100)

for guesses in count(1):
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        break

    guess = int(input("Guess again: "))

print(f"You win, and you guessed this number in {guesses} times!")
\$\endgroup\$
3
\$\begingroup\$

This looks to do the job. I would only change the variable naming to be more meaningful in this context to guess for user guess and answer for the generated number.

I would also try to handle erroneous input such as strings instead of numbers being passed.

But besides this is still functionally good :D

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.