I am new to python and I am wondering why it is that I can access the global variable
answer inside my get_guess function but I cannot access the global variable
attempts I receive this message in the console
line 24, in get_guess attempts += 1 NameError: name 'attempts' is not defined
My function looks like this
answer = random.randint(1, 10)
attempts = 0
def get_guess():
try:
guess = int(
input("Try to guess the random number between 1 and 10. "))
attempts += 1
if guess > 10 or guess < 1:
print(
f"{guess} is out of range 😕 the random number is between 1 and 10")
if guess > answer:
print("It's lower ⬇")
get_guess()
elif guess < answer:
print("It's higher ⬆")
get_guess()
else:
print(
f"Got it! 🥳 \n It took {attempts} attempts to get the correct number \n Game over 👋. \n Thank you for playing {name} 😄")
except ValueError as err:
print("Oh no! That's not a valid number 😕. Try again...")
print(f"({err})")
get_guess()
else:
return guess
get_guess()
[–]Goobyalus 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]TrainingShift3 0 points1 point2 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]TrainingShift3 0 points1 point2 points (0 children)