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!")
Sᴀᴍ Onᴇᴌᴀ
29.6k16 gold badges45 silver badges203 bronze badges
asked May 5, 2021 at 17:14
\$\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!")
answered May 6, 2021 at 10:20
\$\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

answered May 5, 2021 at 18:50
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.