Python Conditions & if Statements

What are the Conditions?

Conditions are expressions that evaluate to True or False, allowing your code to make decisions and execute different actions based on those evaluations. They are essential for creating programs responding to various inputs and scenarios.

The condition can be any logical expression formed using:

1. Comparison Operators:

Used to compare values:

== (equal to)
!= (not equal to)
< (less than)
> (greater than)
<= (less than or equal to) = (greater than or equal to)

Example: if age >= 18:

2. Logical Operators:

Combine multiple conditions:

and (both conditions must be True)
or (at least one condition must be True)
not (inverts the truth value of a condition)

Example: if grade == “A” or grade == “B”:

3. Membership Operators

These check if an element is present in a sequence. Examples include in (checks if an element is in a list) and not in (checks if an element is not in a list).

4. Boolean expressions:

These can be more complex combinations of the above elements.

Check all Python operators here

if Statements:

The “if” statement, in any programming language including Python, plays a crucial role in controlling the flow of your program. It lets you make decisions based on certain conditions.

Here's a comprehensive breakdown of the “if” statement:

if Statements:

Execute code only if a condition is True.


if condition:
    # Code to execute if the condition is True 

# Example: 
if temperature > 40:
    print("It's a hot day!")

if condition: This is the heart of the statement. It's a logical expression that evaluates to True or False.

Code to execute: These are the statements that will be executed if the condition is True (within the if block) or False (within the else block). The else block is optional.

Indentation:

Python uses indentation to define code blocks. Consistent indentation (usually 4 spaces) is crucial for readability and syntax.

Like in the above example you can see there is space in the print statement.

elif Statements:

Allow checking multiple conditions sequentially and execute code only if the previous conditions were False.


if condition1:
    # Code to execute if condition1 is True 
elif condition2:
    # Code to execute if condition1 is False and condition2 is True 

# Example: 

grade = input("Enter your grade: ") 
if grade == "A":
    print("Excellent!") 
elif grade == "B":
    print("Good job!") 
elif grade == "C":
    print("Satisfactory.") 
else:
    print("Needs improvement.")

else Statements:

Execute code if all previous conditions were False. it's an 0ptional companion to if and elif.


if condition:
    # Code to execute if condition is True 
else:
    # Code to execute if condition is False

Nested if Statements:

Place if statements within other if blocks for complex logic.


# Example: 

if has_ticket:
    if ticket_type == "VIP":
        print("Access to VIP lounge.") 
    else:
        print("Access to regular seating.") 
else:
    print("Please purchase a ticket.")

Short Hand if Statement:

Executes a single expression if a condition is True. Combines if and else in a single line.


value = x if condition else y

# Example 

result = "even" if number % 2 == 0 else "odd"

Using Logical Operators in if Statements:

Combine multiple conditions using and, or, and not.

Logical operators in if statements let you write concise, specific, and readable conditionals to handle diverse scenarios and optimize code.


if age >= 18 and has_license:
    print("You can drive.")

another example


if a > b and a > c:
    print("a is greater") 
elif b > c:
    print("b is greater") 
else: 
    print("c is greater")

Using in Operators in if Statement

The in-operator in Python allows you to check if an element exists within a sequence like a list, string, or tuple. It's commonly used in if statements to make decisions based on membership.

Here are some real-time examples:

Example 1

Validating user input:



valid_chars = "abcdefghijklmnopqrstuvwxyz" 
letter = input("Enter a letter: ") 

if letter in valid_chars:
    print(f"{letter} is a valid lowercase letter.") 
else:
    print("Invalid input. Please enter a lowercase letter.")

Example 2:

Checking item availability in a store:



shopping_cart = ["apples", "milk", "bread"] 
item = input("What item are you looking for? ") 

if item in shopping_cart:
    print(f"Yes, we have {item} in stock!") 
else:
    print(f"Sorry, we don't have {item} in stock.")

Example 3:

Filtering data based on specific criteria:


fruits = ["apple", "banana", "orange", "grape"] 
citrus_fruits = ["lemon", "lime", "grapefruit"] 

if "grape" in fruits and "grape" not in citrus_fruits:
    print("Grape is in the fruits list but not in the citrus fruits list.")

Example 4:

Validating passwords with specific requirements:


password = input("Enter your password: ") 
required_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 

if len(password) >= 8 and any(char in required_chars for char in password):
    print("Password is valid.") 
else:
    print("Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, and one digit.")

Identity Operators in if Statements: Checking Object References, Not Values

While the in operator checks if an element exists within a sequence, identity operators in Python (is and is not) compare object references themselves, not the values they hold. This distinction becomes crucial when dealing with mutable objects in if statements.

Example

Checking for the same object


x = [1, 2, 3] 
y = x  # Same object reference 
z = [1, 2, 3]  # Different object with same values 

if x is y:
    print("x and y are the same object")  # True 
else:
    print("x and y are different objects") 

if x is z:
    print("x and z are the same object")  # False 
else:
    print("x and z are different objects")  # True

Example 2:


a = [1, 2, 3] 
b = [1, 2, 3] 

if a is b:
    print("a and b are the same object") 
else:
    print("a and b are different objects")  # True 

a.append(4) 

if a is b:
    print("a and b are still the same object")  # False now! 
else:
    print("a and b are now different objects")  # True because modifying a changed its reference

pass Statement:

Used as a placeholder when a statement is required syntactically but no action is needed.


# Example: 

if age > 13:
    pass # Do nothing for kids 
else:
    print("Welcome!")

Here are some real-time examples of how you can use it:

Empty Blocks:

In conditional statements like if, elif, and else, sometimes you have empty blocks where you haven't decided what to do yet.


if age >= 18:
    # Grant access 
    pass 
else:
    # Handle underage user 
    pass

Incomplete Code Stubs:

For incomplete code structure, pass holds the place while avoiding errors.


def cal_salary():
    # Implementation here... 
    pass

Loop Control:

pass in loops: skipping iterations, keeping structure


for item in items:
    if item.is_hidden:
        pass  # Skip hidden items 
    else:
        # Process visible items 
    pass

if Statement Exercises

Write a program that checks if a number is positive or negative.


num = int(input("Enter a number: ")) 
if num > 0:
    print("The number is positive.") 
else:
    print("The number is zero.")

Write a program that checks if a number is positive, negative, or zero.


num = int(input("Enter a number: ")) 
if num > 0:
    print("The number is positive.") 
elif num < 0:
    print("The number is negative.") 
else:
    print("The number is zero.")

Write a program that determines the discount applicable based on age (child, teenager, adult, senior).



age = int(input("Enter your age: ")) 

if age <= 12:
    discount = 50  # Child discount 
elif age <= 18:
    discount = 25  # Teenager discount 
elif age <= 65:
    discount = 10  # Adult discount 
else:
    discount = 15  # Senior discount 

print("Your discount is", discount, "%")

Write a program that tells if a person is eligible to vote based on their age (voting age is 18).


age = int(input("Enter Age: ")) 
r = "yes" if age >= 18 else "no" 
print(r)

Unsolved if Statement Exercises

  1. Write a program that checks if a given character is a vowel, consonant, or something else.
  2. Write a program that tells if a person is eligible to vote based on their age (voting age is 18).
  3. Write a program that determines the absolute value of a number (non-negative version).
  4. Write a program that checks if a student is eligible for a scholarship based on their GPA and financial aid requirement.
  5. Write a program that determines the grade letter based on a student's score, considering bonus points and rounding rules. ( score > 90: grade is A, score > 80: grade is B, score > 70: grade is C, score > 60: grade is D and less than 60 grade is F)

Python Quiz

Print “Welcome!” if the user's age is 18 or above.
Which code best achieves this?

a) if age == 18:
b) if age <= 18: c) if age >= 18:

Check if a letter is a vowel.
Which code would you use?

a) if letter in “aeiou”
b) if letter == “vowel”
c) if letter == vowel:

You need to check if a user's password is long enough (8 characters or more).
Which code achieves this?

a) if len(password) >= 8: print(“Valid”)
b) if len(password) < 8: print(“Too short”)
c) if len(password) == 8: print(“Valid “)

You need to allow access to a website only for users above 13 and with a valid membership.
Which code correctly represents this check?

a) if age >= 13 and member:
b) if age >= 13 or member:
c) if age > 13 and member == True: