Python if AND
In Python, if statement is a conditional statement that allows us to run certain code only if a specific condition is true. By combining it with the AND operator, we can check if all conditions are true, giving us more control over the flow of our program.
Example : This program checks are you eligible to vote or not .
a = 20 # age
b = True # Citizen status
if a >= 18 and b:
print("Eligible")
else:
print("Ineligible")
Output
Eligible.
We can use the if with AND operator in many ways. Let's understand each one, step by step.
Table of Content
To validate user's input
The most common use case of an if statement with the and operator is to check if the data is correct and meets certain criteria.
Example :
a = 23 # age
b = "yes" # permission
if a >= 18 and b == "yes":
print("Granted")
else:
print("Denied")
Output
Granted
Explanation:
- This code checks if
ais 18 or older andbis "yes". - As both conditions are true, it prints "Granted"
To validate the password
Python if with and operator is mostly use to check a password is strong and enough to keep accounts secure.
Example :
p = "securePass123" #password
if len(p) >= 8 and any(char.isdigit() for char in p):
print("Valid")
else:
print("Invalid")
Output
Valid
Explantion:
- This code checks if
pis at least 8 characters and contains a digit.
Handle Complex Logic in Game Development
Python if with the and operator is commonly used to check multiple conditions such as health and status.
Example :
a = 50 # health
b = True # has_weapon
if a > 0 and b:
print("Fight")
else:
print("No Fight")
Output
Fight
Explanation:
- This code Checks if
ais positive andbisTrue. - Prints "Fight" if both are true.