Control Flow and Logic
22 min read
Real Validation Logic
Real Validation Logic
Many programs need to check if user input is correct before continuing.
This is called validation.
Validation helps stop mistakes and keeps programs safe and useful.
What Is Validation?
Validation means checking data before using it.
For example:
- Is the username empty?
- Is the age a valid number?
- Is the password correct?
- Is the score between 0 and 100?
Why Validation Matters
Without validation, users can enter wrong or missing information.
This can cause errors or bad results.
Example: Empty Name Check
name = input("Enter your name: ")
if name == "":
print("Name cannot be empty")
else:
print("Welcome", name)
Example: Age Check
age = int(input("Enter your age: "))
if age >= 18:
print("Allowed")
else:
print("Not allowed")
Example: Score Range Check
score = int(input("Enter score: "))
if score >= 0 and score <= 100:
print("Valid score")
else:
print("Invalid score")
Example: Password Check
password = input("Enter password: ")
if password == "python123":
print("Login successful")
else:
print("Wrong password")
Code Along
email = input("Enter email: ")
if email == "":
print("Email required")
else:
print("Saved")
Mini Challenge
Build a login checker.
Steps:
- Ask the user to enter a username
- Ask the user to enter a password
- If both are correct, print:
Login successful - Otherwise, print:
Invalid details
Real World Use Case
Websites, mobile apps, banks, and online stores all use validation to check forms, passwords, ages, payments, and user details.
Quiz
- What is validation?
- Why is validation important?
- What happens if data is not checked?
- Name one thing that can be validated.
Assignment
Create a registration checker.
- Ask the user for name and age
- If the name is empty, show an error
- If age is below 18, show
Too young - Otherwise, show
Registration successful
Summary
You learned how validation checks user input, prevents mistakes, and helps build safe and useful Python programs.