You really need a while loop. If the first guess is too high then you get another chance, but it then only tests to see if it is too low or equal. If your guess is too low then your second chance has to be correct.
So you don't need to keep testing, you can simplify, but you should really do this at the design stage. Here is my version:
import random
# from random import randint << no need for this line
print("Welcome to guess the number!")
question = input("Do you want to play the game? ")
if question.lower() == "yes":
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!")
number = random.randint(1, 10)
guess = None # This initialises the variable
while guess != number: # This allows continual guesses
guess = int(input("Take a guess!: ")) # Only need one of these
if guess > number:
print("Your guess is too high")
elif guess < number:
print("Your guess is too low")
else: # if it isn't < or > then it must be equal!
print("Your guess was correct!")
else:
# why do another test? No need.
print("Too bad! Bye!")
# No need for quit - program will exit anyway
# but you should not use quit() in a program
# use sys.exit() instead
Now I suggest you add a count of the number of guesses the player has before they get it right, and print that at the end!
Edit: You will note that my import
statement differs from that given by @Denis Ismailaj. We both agree that only one import
is required, but hold different opinions as to which one. In my version I import random
, this means that you have to say random.randint
whereas in the other you only say randint
.
In a small program there isn't much to choose between them, but programs never get smaller. A larger program, which could easily be importing 6,7,8 or more modules, it is sometimes difficult to track-down which module a function comes from - this is known as namespace pollution. There will be no confusion with a well-known function like randint
, and if you explicitly give the name of the function then it can easily be tracked back. It is only a question of personal preference and style.
With number of guesses added:
import random
print("Welcome to guess the number!")
question = input("Do you want to play the game? ")
if question.lower() == "yes":
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!")
number = random.randint(1, 10)
guess = None
nrGuesses = 0 # Added
# Allow for continual guesses
while guess != number and nrGuesses < 6: # Changed
guess = int(input("Take a guess!: ")) # Only need one of these
nrGuesses += 1 # Added
if guess > number:
print("Your guess is too high")
elif guess < number:
print("Your guess is too low")
else: # if it isn't < or > then it must be equal!
print("Your guess was correct!")
else:
print("Too bad! Bye!")
print("Number of guesses:", nrGuesses) # Added