Welcome to CodeYourCraft's Python Input Validation tutorial! Today, we're going to dive deep into the world of ensuring our Python programs receive correct user input. Let's get started!
Input validation is the process of checking and verifying user-supplied data in a computer program. It helps to ensure that the data is correct, complete, and consistent before it is processed by the program.
Input validation is crucial to prevent errors and ensure the smooth running of your programs. Without proper input validation, your programs can be vulnerable to malicious user input, such as attacks known as SQL injection or Cross-site scripting (XSS).
Let's start by validating simple user input using Python's built-in input() function and some basic comparison operators.
# Ask the user to enter a number
number = input("Enter a number: ")
# Check if the input can be converted to a number
if number.isnumeric():
number = int(number)
print("You entered:", number)
else:
print("Invalid input. Please enter a number.")š Note: The isnumeric() function checks if a string contains only digits.
# Ask the user to enter a string
string = input("Enter a string: ")
# Check if the length of the string is more than zero
if len(string) > 0:
print("You entered:", string)
else:
print("Invalid input. Please enter a string.")š Note: The len() function returns the length of a string.
Now that we've covered the basics, let's move on to more advanced techniques for input validation.
import re
# Ask the user to enter an email address
email = input("Enter an email address: ")
# Regular expression pattern for a valid email address
email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
# Check if the email matches the pattern
if re.match(email_pattern, email):
print("You entered a valid email address.")
else:
print("Invalid email address.")š Note: The re module in Python provides powerful regular expression matching operations.
How can we check if a string contains only digits in Python?
Today, we've learned the importance of input validation in Python and how to validate basic and advanced user input. By using Python's built-in functions and the re module, we can ensure our programs receive correct user input and run smoothly. Keep practicing, and happy coding! š»š