Title: What is the Pythonic way to handle invalid user input in a while loop?

4 days ago 13
ARTICLE AD BOX

import random

number_to_guess = random.randint(1, 10)

while True: guess = input("Guess a number between 1 and 10: ")

# This crashes if 'guess' is not a number if int(guess) == number_to_guess: print("You won!") break else: print("Wrong, try again.") **The Problem:** If I enter `hello`, I get: `ValueError: invalid literal for int() with bas

What is the correct way to validate this input so the program prints "Please enter a valid number" instead of crashing? Should I use a try/except block or check guess.isdigit()?

Read Entire Article