0

Why is my code not working(Updated)

import random defnumber_guessing_game(): print("Welcome to the Number Guessing Game!") number_to_guess = random.randint(1, 100) attempts = 0 while True: try: guess = int(input("Guess a number between 1 and 100: ")) attempts += 1 if guess < number_to_guess: print("Too low! Try again.") elif guess > number_to_guess: print("Too high! Try again.") else: print(f"🎉 Correct! The number was {number_to_guess}.") print(f"You guessed it in {attempts} attempts.") break except ValueError: print("Please enter a valid number.") if __name__ == "__main__": number_guessing_game()

11th Sep 2025, 2:54 AM
Andreas Nick
3 ответов
+ 3
Woah, you are really good at Python! I tested the game and it's interesting! The error is due to a small typo in the 3rd line: defnumber_guessing_game(): You forgot to add a space " " between "def" and "number_guessing_game():". Just make it: def number_guessing_game(): And it's all done! Additional Suggestion: Your code uses and Infinite loop, and if the user fails to guess the number, it throws an EOFError because it again expects the user to input something. For this, you can add another except block for ending the program if the user fails to guess the number: except EOFError: print("Looks you gave up. Well, the number was " + str(number_to_guess)) And it's all done 🎉 Additionally for Sololearn playground, as it asks for all inputs at once, you can add a "\n" to the input statements. Here's the corrected version for you: https://sololearn.com/compiler-playground/czu31r7ItqJM/?ref=app
11th Sep 2025, 3:11 AM
Unknown Decoder
Unknown Decoder - avatar
+ 2
maybe put a space between def and the function name. def number_guessing_game(): also, these type of looping input does not work in Sololearn. all inputs have to be given at the input box before the program runs, so you can't see the hints in between, too.
11th Sep 2025, 3:04 AM
Bob_Li
Bob_Li - avatar
+ 2
Thank you🤩!
11th Sep 2025, 3:05 AM
Andreas Nick