I am trying to built number guessing game. I created a game()
function that first lets you pick difficulty level and according to the level loops through in that amount and asks for users to guess. My problem here is getting out of the loop. I created a boolean named is_continue
, set it to True
, and wanted to use it whenever it needs to be broken out of the loop (which are when you guessed the right number and when you want to end the game), but not only is it not breaking out of the loop but also it keeps re-looping even though the range amount is completed.
from random import randint
from replit import clear
value = randint(1, 100)
def compare(guess, value):
if guess > value:
print("Too high.")
elif guess < value:
print("Too low.")
else:
print(f"You got it! The answer was {value}")
def game():
print("Welcome to the number guessing game.")
print("I am thinking of a number between 1 and 100.")
difficulty_level = input("Choose a difficulty. Type 'easy' or 'hard'.")
is_continue = False
while not is_continue:
if difficulty_level == "easy":
e_attempt = 10
for x in range (10):
print (f"You have {e_attempt} attempts.")
e_attempt -= 1
guess = int(input("Guess a number?"))
compare(guess, value)
if guess == value:
is_continue = True
if x == 9:
print("You've run out of guess. You lose.")
if input("Type 'c' to continue and 'e' to end.") == "c":
clear()
game()
else:
# I put print function to check weather else statement is working.
print("else statement has been read.")
is_continue = True
elif difficulty_level == "hard":
h_attempt = 5
for x in range (5):
print (f"You have {h_attempt} attempts.")
h_attempt -= 1
guess = int(input("Guess a number?"))
compare(guess, value)
if guess == value:
is_continue = True
if x == 4:
print("You've run out of guess. You lose.")
if input("Type 'c' to continue and 'e' to end.") == "c":
clear()
game()
else:
clear()
clear()
game()
When you asign value True
to is_continue
variable it will not break out of your while loop. You can type break
to break out of for loop that is currenty running and on next iteration of while loop it will not execute because the value of is_continue
variable is set to True
.
Code example:
while not is_continue:
if difficulty_level == "easy":
e_attempt = 10
for x in range (10):
print (f"You have {e_attempt} attempts.")
e_attempt -= 1
guess = int(input("Guess a number?"))
compare(guess, value)
if guess == value:
is_continue = True
break # this was added
Keep in mind that asigning a value to variables in while loop is not a good thing in this example. The variable difficulty_level
will never change throughout your code. After your for loop ends, it will actually start again. break
is a great way to break out of current loop you are into, especially when using nested loops.
I hope my answer helps and good luck coding!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments