Conditional Statements in Python

Conditional statements in Python allow us to control the flow of execution based on conditions. In this post, we’ll explore different ways to use if, if-else, logical operators, and inline decision-making.

Basic if Condition

The if statement executes a block of code only if the given condition is True.

if True:
    print("Statement is true")  # Output: Statement is true

if False:
    print("Statement is false")  # No output

Example: Checking a Number

x = 20
if x > 10:
    print("X is greater than 10")  # Output: X is greater than 10

x = 20
if x < 10:
    print("X is less than 10")  # No output

Example: Checking Membership in a List

L = [10, 20, 30, 40, 50]
if 20 in L:
    print("20 is a member of L")  # Output: 20 is a member of L

Using if-else Condition

If the condition is True, the if block executes; otherwise, the else block runs.

x = 20
if x > 10:
    print("X is greater than 10")  # Output: X is greater than 10
else:
    print("X is less than 10")

Example: Checking Even or Odd Number

values = {}

x = int(input("Enter a value: "))  # Example: Input 8
if x % 2 == 0:
    values[str(x)] = "Even"
else:
    values[str(x)] = "Odd"

print(values)  # Output: {'8': 'Even'}

Using if-elif-else Condition

This structure allows checking multiple conditions one after another.

mark = 75
if mark >= 80:
    Grade = "A"
elif mark >= 65:
    Grade = "B"
elif mark >= 50:
    Grade = "C"
else:
    Grade = "Repeat"

print(Grade)  # Output: B

Logical Operators in Conditions

Python supports logical operators like and, or, and not for decision-making.

x = 30
if x > 10 and x < 50:
    print("X is in the correct region")  # Output: X is in the correct region
else:
    print("X is out of the region")
x = 30
if x > 10 or x == 50:
    print("X is in the correct region")  # Output: X is in the correct region
x = 30
if not x > 10 or x == 50:
    print("X is in the correct region")
else:
    print("X is out of the region")  # Output: X is out of the region

User Authentication Example

Here’s an example of a simple login system:

details = {"Sam": "ABC", "Kane": "XYZ", "Jane": "PQR"}

username = input("Please enter your username: ")
if username in details:
    password = input("Please enter your password: ")
    if password == details[username]:
        print("You have logged in successfully!!!")
    else:
        print("Check your password...")
else:
    print("You are not in the system. Please check your username again")

Inline Decision Making (Ternary Operator)

Python allows short-hand conditions using the ternary operator.

x = 20
y = 10
if x > 10: y = 30
print(y)  # Output: 30
fruit = 'Apple'
check_apple = "Yes" if fruit == 'Apple' else "No"
print(check_apple)  # Output: Yes
mark = 90
result = "Pass" if mark >= 50 else "Fail"
print(result)  # Output: Pass
mark = 90
grade = "A" if mark >= 80 else "B" if mark >= 65 else "C" if mark >= 50 else "F"
print(grade)  # Output: A