Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python "Guess the number" game

this is my first post in StackOverFlow and I’m sure. that I can find for 100% percent an answer for it, but I’d really like to start my adventure with programming and know that this community might help me with it.

My q’s is:

I wrote that first piece of code but I’d like to add here a function where the user writes the guess number bigger than the first one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am troubled with adding the additional function "if" for this situation – I do understand that it wouldn’t suppose to be if, but "elif".
Is anyone has any idea how to suppose to look-alike??

Thanks for any advice

top_range = input("Write a number bigger then 0: ")
if top_range.isdigit() or top_range[0] == "-":
 top_range = int(top_range)
 if top_range <= 0:
     print('Write a number bigger then 0')
     quit()
else:
 print('Write a number bot a word')
 quit()
 random_number = random.randint(0, top_range)
guesses = 0
while True:
 guesses += 1
 user_guess = input("Guess the number : ")
 if user_guess.isdigit():
         user_guess = int(user_guess)
 else:  
     print('Write another number.')
     continue    
 if user_guess == random_number:
     print('You did it!')
     break
 else:
     if user_guess < random_number:
       print('The number is bigger then that')
     else:
       print('The number is smaller than that')        
print('You did it in', guesses, "guesses!")```

>Solution :

Add a first if, then use elif for the other choices. I’ve also simplify a bit the first if

while True:
    guesses += 1
    user_guess = input("Guess the number : ")
    if not user_guess.isdigit():
        print('Write another number.')
        continue

    user_guess = int(user_guess)

    if user_guess > top_range:
        print("That is higher than top range, try again")
    elif user_guess == random_number:
        print('You did it!')
        break
    elif user_guess < random_number:
        print('The number is bigger then that, try again')
    else:
        print('The number is smaller than that, try again')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading