Introduction:

When building interactive programs, such as games or applications that rely on user input, it’s important to ensure that the data entered is correct and within expected boundaries. This is called input validation. Python provides various ways to check whether user input meets certain criteria, ensuring that the program can proceed without errors or unexpected behaviour.

Why is Input Validation Important?

Imagine a scenario where a program asks the user to pick a number between 1 and 10. What happens if the user enters a number like 25 or types a word instead of a number? Without proper input validation, the program might break or give incorrect results. By validating inputs, we make sure the user only enters data that is usable for the program.

Real-World Example: Let’s say you’re filling out an online form to register for an event, and the form asks you for your age. If you accidentally type in letters instead of numbers, the website would return an error, asking you to enter a valid age. Similarly, it may ask for your email address, and if it doesn’t include the ‘@’ symbol, it would tell you that the input is incorrect. This is all part of input validation in action.

When writing Python programs, it's crucial to include checks like these so that users don’t accidentally "break" your program by entering bad data.

Key Aspects of Input Validation:

  1. Data Type: Ensure that the data entered is of the correct type (e.g., numbers, text).
  2. Range: Check that numbers or values fall within an expected range (e.g., a number between 1 and 100).
  3. Length: Ensure text inputs, like passwords, meet minimum and maximum length requirements.
  4. Format: For inputs like emails or phone numbers, ensure that the data fits a specific format.

Example: Validating Age Input

Let’s look at a simple example of how you can validate a user’s input in Python. Imagine you’re writing a program that asks the user for their age. You want to make sure the input is a valid number and that the age falls within a reasonable range (say, between 0 and 120).

age = input("Enter your age: ") # Check if the input is a number
if age.isdigit():
    age = int(age) # Convert the string to an integer
    # Check if the age is within the valid range
    if age < 0 or age > 120:
        print("Please enter a valid age between 0 and 120.")
    else:
        print("Thank you for entering your age.")
else:
    print("Invalid input. Please enter a number.")

Breaking Down the Code:

  • Line 1: We ask the user to input their age. However, remember that input() always returns the data as a string, even if the user types a number.
  • Line 2: We use the .isdigit() method to check if the input is a valid number. If the user types letters or symbols, this check will fail, and the program will return an error message.
  • Line 3: If the input is valid (i.e., a number), we then convert the string into an integer.
  • Lines 5-8: We check if the number is within the expected range (in this case, between 0 and 120). If it’s not, the program tells the user to enter a valid age. If it’s within the range, the program proceeds.

Real-World Example Expanded:

Let’s imagine a different scenario. Suppose you are creating a game where the player needs to guess a number between 1 and 100. You want to make sure they only enter a number within this range, and also make sure they don’t type something else, like "hello" or "!" that could cause an error.

guess = input("Guess a number between 1 and 100: ")
# Check if the input is a number
if guess.isdigit():
    guess = int(guess)
    # Check if the number is within the valid range
    if guess < 1 or guess > 100:
        print("Out of range! Please guess a number between 1 and 100.")
    else:
        print("Good guess!")
else:
    print("Invalid input! Please enter a number.")

Input Validation in More Detail:

Now let’s dive a bit deeper. Input validation is not just limited to numbers. You can validate many types of input in a variety of ways. For instance, validating text input like passwords, usernames, or even making sure that an email address includes an "@" symbol.

Validating String Length:

When creating passwords, websites often ask you to ensure that your password is at least 8 characters long. In Python, we can easily check this with the len() function.

password = input("Enter a password (at least 8 characters): ") 
# Check if the password is long enough
if len(password) < 8:
    print("Your password is too short! It must be at least 8 characters.")
else:
    print("Password accepted.")

Validating Email Format:

In real-world applications, you often need to check that input data fits a specific pattern. For example, you might want to make sure an email address contains an "@" symbol. Here's a basic example:

email = input("Enter your email address: ")
# Check if the email contains "@" and "."
if "@" in email and "." in email:
    print("Email is valid.")
else:
    print("Invalid email format. Please enter a valid email address.")

Wrapping Up:

Input validation is a fundamental aspect of programming that helps ensure that the data your program receives is clean and correct. This not only prevents errors but also enhances the user experience by providing clear and helpful error messages when things go wrong.

By ensuring that inputs meet certain criteria—such as being within a valid range, of the correct type, or the right length—you can build more robust and reliable programs.

Always remember: The more we validate the input, the safer and more predictable our program becomes!

Predict:

Take a look at this piece of code. What do you think will happen when the user enters a number that is too high?

number = int(input("Pick a number between 1 and 10: "))
if number < 1 or number > 10:
    print("Out of range! Please choose a number between 1 and 10.")
else:
    print("Thank you for choosing", number) 

Try to predict how this code will respond to different inputs. What if the user enters 11? Or 0?

Run:

Now, it’s your turn to run some code! Let’s see how Python validates input by running this example in the embedded IDE.

Run the code and try entering different numbers. What happens when you enter a number within the range? How does it behave with numbers outside of the range?

Investigate:

Let's dig a bit deeper! Below is a slightly modified version of the code. Can you spot any differences in how it works? Run the code and observe how the output changes based on the input you provide.

Instructions: Try entering non-numeric values (like letters or symbols). What do you observe?

Modify:

It’s time to make some changes! In the code below, the input is checked, but there’s a mistake preventing it from working properly. Can you spot and fix the problem?

Hint: Look carefully at the conditions. Should the age limit be 1500?

Scroll to Top