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

Random number game in python, with according messages

I am trying to make a random-number game, where you have to guess which random number Python gets from 1-10. And also do so that if you write e.g. 11, 104 etc. it will ask you to try again to write a valid input.

This is what I have tried so far, but I cant seem to figure out what I have done wrong. All help is greatly appreciated:)
Sorry if it is an easy question, I am still fairly new to Python

while True:
    try:
        number_in = int(input("Please insert a number between 1-10: "))
    except ValueError:
            print("Sorry. Try again to insert a number from 1 to 10")
            continue
            
if 1 < number <10:
    print("Your input was invalid. Please insert a number from 1 to 6")
    continue
else:
    break

game_1 = randint(1,10)

if number_in == game_1:
    print(f"The result was {game_1}. Your guess was correct, congratulations!")
else:
    print(f"The result was {game_1}. Your guess was NOT correct. Try again")

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

>Solution :

Lots of small mistakes, here is a working solution. I’ll try to talk you through it:

import random

while True:
    try:
        number_in = int(input("Please insert a number between 1-10: "))
        if 1 <= number_in <= 10:
            break
        else:
            print("Your input was invalid. Please insert a number from 1 to 10")
    except ValueError:
        print("Sorry. Try again to insert a number from 1 to 10")

game_1 = random.randint(1, 10)

if number_in == game_1:
    print(f"The result was {game_1}. Your guess was correct, congratulations!")
else:
    print(f"The result was {game_1}. Your guess was NOT correct. Try again")
  1. You need to break from the loop when a correct input is met
  2. Continue within the except block is redundant – it will continue to the next iteration nevertheless
  3. break and continue are keywords used only inside a loop
  4. Conditional should be inside the loop
  5. Conditional has wrong variable name (number_in != number)
  6. Conditional was upside down (number in between 1 and 10 -> "wrong input")
  7. Wrong comparison used in conditional. You want to include 1 and 10 as guesses so <= instead of <
  8. import random was missing from the example code
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