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")
>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")
- You need to break from the loop when a correct input is met
- Continue within the
exceptblock is redundant – it will continue to the next iteration nevertheless breakandcontinueare keywords used only inside a loop- Conditional should be inside the loop
- Conditional has wrong variable name (
number_in != number) - Conditional was upside down (number in between 1 and 10 -> "wrong input")
- Wrong comparison used in conditional. You want to include 1 and 10 as guesses so
<=instead of< import randomwas missing from the example code