If Statements in Python


While writing code in any language, you will have to control the flow of your program - you will want to execute a certain piece of code if a condition is satisfied, and some different code in case it is not.


If Statement

If statements are used to make these decisions in code. The keyword if tells Python to execute the block of lines indented the same amount after the colon (:) under certain conditions. These conditions are known as Boolean conditions and they may only be True or False.

When the condition evaluates to True, the program executes that block of lines; when the Boolean condition evaluates to False, that block of lines will not execute. For example:

myVar = 5
if myVar < 10:
    print("Passed the test.")

The code above prints "Passed the test." since myVar < 10 evaluates to true, but this code:

myVar = 5
if myVar % 2 == 0:
    print("Passed the test.")

prints nothing since myVar % 2 == 0 evaluates to false.


Else Statement

With an else statement, an alternate block of code can be executed when the condition inside the if evaluates to false. For example:

myVar = 5
if myVar % 2 == 0:
    print("Passed the test.")
else:
    print("Failed the test.")

The code above prints "Failed the test." since myVar % 2 == 0 evaluates to false and we enter the else statement.


Comparison Operators

When writing if statements, we usually compare two values using one or more comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

Let's see some examples:

a = 2
b = 3

if a == b:
    print("a equals b")

if a < b:
    print("a is less than b")

The code above prints "a is less than b".


Combining conditional statements

We can also combine multiple conditional statements with the help of logical operators:

Operator Description Examples
and Returns True if both statements are True x < 5 and x >= 2
or Returns True if one of the statements is True x < 5 or x > 1
not Reverses the result, returns False if the result is True not (x < 5 and x > 1)

Let's see some examples:

a = 2
b = 3

# Prints "b equals 3"
if a == 2 and b - a == 1:
  print("b equals 3")

# Prints "a = 2, b = 3"
if a != 2 or b != 3:
  print("Inside if")
else:
  print("a = 2, b = 3")

# Prints "a + b equals 5"
if !(a + b == 5):
  print("a + b is not equal to 5")
else:
  print("a + b equals 5")

The "elif"

Also, in Python, when you have an else statement followed immediately by an if, you can use elif keyword:

if condition1:
    # run code for condition 1
elif condition2:
    # run code for condition 2
else:
    # run this code if both conditions fail

Nested conditionals

A nested conditional statement is an if or if else statement inside another if else statement:

a = 2
b = 3

if a % 2 == 0:
  if b % 2 == 0:
    print("Both a and b are even")
  else:
    print("a is even, b is odd")
elif b % 2 == 0:
    print("a is odd, b is even")
else:
    print("Both a and b are odd")

The code above prints "a is even, b is odd".


Assignment
Follow the Coding Tutorial and let's write some if-else statements.


Hint
Look at the examples above if you get stuck.


Introduction

In programming, controlling the flow of your program is essential. One of the fundamental ways to achieve this is through the use of if statements. These statements allow you to execute specific blocks of code based on certain conditions. Understanding how to use if statements effectively is crucial for writing efficient and logical code.

Understanding the Basics

At its core, an if statement evaluates a condition, which is a Boolean expression that can either be True or False. If the condition is True, the code block following the if statement is executed. If the condition is False, the code block is skipped.

Consider the following example:

myVar = 5
if myVar < 10:
    print("Passed the test.")

In this example, the condition myVar < 10 evaluates to True, so the message "Passed the test." is printed.

Main Concepts

Let's delve deeper into the key concepts and techniques involved in using if statements:

Comparison Operators

Comparison operators are used to compare two values. Here are some common comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

Logical Operators

Logical operators allow you to combine multiple conditions. The most common logical operators are:

Operator Description Examples
and Returns True if both statements are True x < 5 and x >= 2
or Returns True if one of the statements is True x < 5 or x > 1
not Reverses the result, returns False if the result is True not (x < 5 and x > 1)

Examples and Use Cases

Let's explore some examples to see how if statements can be used in various contexts:

Example 1: Simple Comparison

a = 2
b = 3

if a == b:
    print("a equals b")

if a < b:
    print("a is less than b")

In this example, the second condition a < b evaluates to True, so "a is less than b" is printed.

Example 2: Using Else

myVar = 5
if myVar % 2 == 0:
    print("Passed the test.")
else:
    print("Failed the test.")

Here, the condition myVar % 2 == 0 evaluates to False, so the else block is executed, printing "Failed the test."

Example 3: Combining Conditions

a = 2
b = 3

if a == 2 and b - a == 1:
    print("b equals 3")

if a != 2 or b != 3:
    print("Inside if")
else:
    print("a = 2, b = 3")

In this example, the first condition a == 2 and b - a == 1 evaluates to True, so "b equals 3" is printed. The second condition a != 2 or b != 3 evaluates to False, so the else block is executed, printing "a = 2, b = 3".

Common Pitfalls and Best Practices

When working with if statements, it's important to be aware of common mistakes and follow best practices:

Common Pitfalls

Best Practices

Advanced Techniques

Once you're comfortable with basic if statements, you can explore more advanced techniques:

Elif Statements

The elif keyword allows you to check multiple conditions in sequence:

if condition1:
    # run code for condition 1
elif condition2:
    # run code for condition 2
else:
    # run this code if both conditions fail

Nested Conditionals

You can nest if statements within each other to create more complex logic:

a = 2
b = 3

if a % 2 == 0:
    if b % 2 == 0:
        print("Both a and b are even")
    else:
        print("a is even, b is odd")
elif b % 2 == 0:
    print("a is odd, b is even")
else:
    print("Both a and b are odd")

Code Implementation

Let's implement a simple program that uses if statements to determine if a number is positive, negative, or zero:

# Function to check if a number is positive, negative, or zero
def check_number(num):
    if num > 0:
        return "Positive"
    elif num < 0:
        return "Negative"
    else:
        return "Zero"

# Test the function
print(check_number(10))  # Output: Positive
print(check_number(-5))  # Output: Negative
print(check_number(0))   # Output: Zero

Debugging and Testing

Debugging and testing are crucial steps in ensuring your code works as expected:

Debugging Tips

Writing Tests

Writing tests helps you verify that your code works correctly. Here's an example of how to write tests for the check_number function:

def test_check_number():
    assert check_number(10) == "Positive"
    assert check_number(-5) == "Negative"
    assert check_number(0) == "Zero"
    print("All tests passed!")

# Run the tests
test_check_number()

Thinking and Problem-Solving Tips

When approaching problems related to if statements, consider the following strategies:

Conclusion

Mastering if statements is essential for controlling the flow of your programs. By understanding the basics, exploring advanced techniques, and following best practices, you can write efficient and logical code. Keep practicing and experimenting with different scenarios to strengthen your skills.

Additional Resources

For further reading and practice, consider the following resources: