“Introduction to Python Programming” Learning Path
Conditional Statements in Python
Conditional statements are used to make decisions in a program. They allow the program to execute different blocks of code based on certain conditions in Python.
if statement
it executes code only if the condition is True.
age = 18
if age >= 18:
print("You can vote")You can voteif-else statement
It executes one block if condition is true, otherwise another.
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")Minorif-elif-else statement
It is used when there are multiple conditions.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")Grade BNested Conditions
Nested conditions mean using an if statement inside another if.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Underage")Entry allowedPractical Decision Making Examples
Example 1: Find if a number is even or odd number
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")Odd numberExample 2: Find the largest of two numbers
a = 10
b = 20
if a > b:
print("a is greater")
else:
print("b is greater")b is greaterExample 3: Create a simple Login System code.
username = "admin"
password = "1234"
if username == "admin" and password == "1234":
print("Login successful")
else:
print("Invalid credentials")Login successfulExample 4: Check if a number is Positive, Negative or Zero
num = -5
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")Negative