I'm fairly new to programming so I'd appreciate the help of the community. I wrote a code to a simple number guessing game, and everything works just fine until the user enters a number that is out of the specified range, which activate a while loop preventing them to do exactly that. Here is my code:
# Guessing name where computer thinks a number and user is to guess it.
import random
def guess_number():
number1 = int(input("Input first number of the range: "))
number2 = int(input("Input second number of the range: "))
if number1 > number2:
number1, number2 = number2, number1
numbers = list(range(number1, number2))
numbers.append(number2)
number_to_guess = random.choice(numbers)
def user_guess_func():
user_guess = int(input("Guess the number from the range: "))
while user_guess not in numbers:
print("That is not in the range.")
user_guess_func()
else:
if user_guess == number_to_guess:
print(f"{user_guess} = {number_to_guess}! You have won.")
else:
print(f"{user_guess} != {number_to_guess}! You have lost.")
user_guess_func()
def play_again_func():
play_again = input("Wanna play again? Yes, or no?")
if play_again == "Yes":
guess_number()
elif play_again == "No":
print("Goodbye!")
else:
print("That is not an answer.")
return play_again_func()
play_again_func()
guess_number()
I understand that integers are immutable and the while loop only creates references to variables so every previous iteration of the user_guess being out of the range lingers there unresolved. However, although I've browsed through the answers here, I'm still unsure how to amend my code to "get rid" of the original out-of-range value of the user_guess.
Also I'd like to ask wheter it is a wise approach to write the code of a small program like that, summing all up in one nested definition and then calling the function?
Thank you!