Python is characterized by simple and intuitive syntax, making it one of the first languages many programming beginners learn. Among its features, “conditional branching” is an essential element for controlling program behavior. In this chapter, you will learn about the “if statement,” the fundamental building block of Python’s conditional branching.
The Importance of Conditional Branching in Python
To have a program perform different actions based on specific conditions, conditional branching is required. Python’s if statement is the basic syntax that enables this branching. Understanding it dramatically improves a program’s flexibility and applicability.
Role of the if Statement
if statement executes the specified code only when a particular condition is met. Using this structure allows a program to operate dynamically in response to input or external environments.
2. Basic Syntax of if Statements
Python’s if statement is very simple, and even beginners can understand it intuitively. This chapter explains the basic structure of the if statement and how to use it.
Basic Structure
The basic structure of Python’s if statement is as follows.
if condition:
code_to_execute
Importance of Indentation
In Python, code hierarchy is expressed using indentation. When the condition of an if statement is true, the code to be executed must be indented one level. Example: Correct Indentation
if 10 > 5:
print("10 is greater than 5")
Example: Incorrect Indentation
if 10 > 5:
print("10 is greater than 5") # error
In Python, incorrect indentation causes errors, so you need to be careful.
Condition Expressions
The condition expression used in an if statement is an expression that returns True or False. When the condition expression is True, the code inside the if statement is executed. For example, the following code displays a message because the condition is true.
if 5 == 5:
print("The condition is true")
On the other hand, if the condition is false, the code inside the if statement is ignored.
if 5 != 5:
print("This code will not be executed")
3. Comparison Operators and Logical Operators
Python’s if statements require “comparison operators” and “logical operators” to build conditional expressions. This chapter provides a detailed explanation of each operator and concrete usage examples.
What are Comparison Operators
Comparison operators compare two values and return True or False. Below are the main comparison operators used in Python.
Operator
Meaning
Example
Result
==
equal
5 == 5
True
!=
not equal
5 != 3
True
>
greater than
5 > 3
True
<
less than
5 < 3
False
>=
greater than or equal to
5 >= 5
True
<=
less than or equal to
3 <= 5
True
Example: Conditional branching using comparison operators
x = 10
if x > 5:
print("x is greater than 5")
What are Logical Operators
Logical operators are used to combine multiple conditional expressions. The three logical operators commonly used in Python are listed below.
Operator
Meaning
Example
Result
and
when both conditions are True
5 > 3 and 10 > 5
True
or
when either condition is True
5 > 3 or 10 < 5
True
not
negates the logical value of the condition
not 5 > 3
False
Example: Conditional branching using logical operators
x = 10
y = 20
if x > 5 and y > 15:
print("x is greater than 5, and y is greater than 15")
Combining Comparison and Logical Operators
In if statements, you can handle complex conditions by combining comparison and logical operators. Example: Combining Multiple Conditions
age = 25
income = 50000
if age > 18 and income > 30000:
print("Conditions are met")
In this code, the condition is satisfied when age is 18 or older and income is 30,000 or more.
4. if-else statement
In addition to the basic if statement, the else statement is used to specify processing when the condition is not met. This chapter explains the structure and usage of if-else statements.
Basic structure of if-else statements
if-else statement structure is as follows.
if condition:
process when condition is true
else:
process when condition is false
Example usage
Below is a simple example using an if-else statement. Example: Using an if-else statement
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
In this code, if x is greater than 5, the first message is displayed; otherwise, the else block is executed.
Practical example
The if-else statement is frequently used for dynamic processing based on user input and conditions. Example: Conditional branching based on user input
number = int(input("Please enter a number: "))
if number % 2 == 0:
print("It is even")
else:
print("It is odd")
In this example, the program determines whether the number entered by the user is even or odd and displays a message.
5. if-elif-else statement
When handling multiple conditions, trying to manage them with only if statements can make the code cumbersome. In such cases, using Python’s if-elif-else statement allows you to handle multiple conditions efficiently. This section explains the structure and examples of the if-elif-else statement.
Basic structure of if-elif-else statement
if-elif-else statement has the following structure.
if condition1:
process when condition1 is true
elif condition2:
process when condition2 is true
else:
process when none of the conditions are true
elif is short for “else if” and is used to check multiple conditions in order.
Example usage
Below is a simple example using the if-elif-else statement. Example: Conditional branching based on numeric ranges
In this example, different messages are displayed depending on the value of score.
Importance of elif
Using elif causes conditions to be evaluated sequentially, allowing efficient processing even when multiple conditions overlap. Example: Condition priority
temperature = 30
if temperature > 35:
print("It's a scorching hot day")
elif temperature > 25:
print("It's a hot day")
elif temperature > 15:
print("It's a comfortable day")
else:
print("It's a cold day")
In this code, only the first matching condition is executed, and subsequent conditions are skipped.
Omitting else
else is not mandatory and can be omitted when appropriate. In particular, it can be omitted when it’s not necessary to define handling for all possible conditions. Example: When else is omitted
age = 20
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
6. Nested if statements
When conditions become more complex, you can nest if statements. This chapter explains how to write nested if statements and the points to consider.
Basic structure of nested if statements
The structure of nested if statements is as follows.
if condition1:
if condition2:
process when both condition1 and condition2 are true
Example usage
The following is an example using nested if statements. Example: Combining two conditions
age = 25
income = 40000
if age > 18:
if income > 30000:
print("You are an adult and your income is sufficient")
else:
print("You are an adult but your income is insufficient")
else:
print("You are a minor")
This code evaluates by combining age and income conditions.
Cautions
If you overuse nesting, the code can become hard to read. Therefore, it’s important to keep it concise by separating conditions or using logical operators. Example: Simplify nesting
age = 25
income = 40000
if age > 18 and income > 30000:
print("You are an adult and your income is sufficient")
elif age > 18:
print("You are an adult but your income is insufficient")
else:
print("You are a minor")
7. Conditional Expression Short Form (Ternary Operator)
In Python, you can use the ternary operator to write simple conditional branches in a single line. This chapter explains the basic syntax, usage examples, and cautions for the ternary operator.
Basic Syntax of the Ternary Operator
The ternary operator is written with the following syntax.
value1 if condition else value2
condition is True, value1 is returned.
condition is False, value2 is returned.
Examples
Example: Number Classification
x = 10
result = "positive number" if x > 0 else "negative number"
print(result)
In this code, if x is greater than 0, it displays “positive number”; otherwise, it displays “negative number”. Example: Maximum Value Determination
a, b = 5, 10
max_value = a if a > b else b
print(f"The maximum value is {max_value}")
In this example, it determines which of a and b is larger and assigns that value to max_value.
Nested Ternary Operators
Ternary operators can be nested, but be careful as the code can become hard to read. Example: Nested Ternary Operator
x = 0
result = "positive number" if x > 0 else "negative number" if x < 0 else "zero"
print(result)
In this code, it determines whether x is a positive number, a negative number, or zero.
Notes
The ternary operator is concise and convenient, but it is not suitable for complex conditions. When conditions are complex, using a regular if-else statement improves readability.
Overusing the ternary operator can reduce code readability, so aim to use it only in appropriate situations.
8. Precautions for if Statements
Python’s if statement requires understanding several characteristics and cautions. This chapter explains points to prevent common mistakes and problems.
Evaluation of None and Empty Values
In Python, None and empty values (empty strings, empty lists, etc.) are evaluated as False. Example: Evaluation of None
x = None
if not x:
print("x is None")
Example: Evaluation of Empty Values
items = []
if not items:
print("The list is empty")
is and == Differences
== compares value equality.
is compares object identity (whether they are the same object in memory).
Example: Differences between is and ==
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (values are equal)
print(a is b) # False (objects are different)
Cautions for Conditional Expressions
When conditional expressions become complex, it’s good to use parentheses to clarify precedence. Example: Conditional Expression Using Parentheses
x = 10
y = 5
if (x > 5 and y < 10) or x == 10:
print("Condition is met")
9. Summary
In this series, we have learned the basics to advanced topics of Python’s if statements. In this chapter, we will review what we have covered so far and organize the key points.
Fundamentals of Python if Statements
if statements execute specific code only when the condition is True.
In Python, indentation determines code structure, so proper indentation is essential.
Basic Syntax
if condition:
code_to_execute
Extending Conditional Branching
Using if-else statements allows you to specify handling for when the condition is False.
With if-elif-else statements, you can efficiently handle multiple conditions.
By combining comparison and logical operators, you can express more complex conditions.
Using nested if statements allows you to handle hierarchical conditions.
Example: Complex Condition
age = 25
income = 50000
if age > 18 and income > 30000:
print("Condition met")
Using the Ternary Operator (Conditional Expression)
Use the ternary operator to write simple conditional branches in a single line.
However, for complex conditions it’s better to use a regular if-else statement.
Example: Ternary Operator
result = "Pass" if score >= 60 else "Fail"
Things to Note
Empty values and None are treated as False.
Understand the difference between is and == and use them appropriately.
When conditions become complex, using parentheses to clarify precedence is important.
Next Steps
Python’s if statements are not only fundamental for learning conditional branching but also a crucial tool for greatly enhancing program flexibility. As the next step, we recommend moving on to the following topics.
Combining Loops and Conditional Branching
Learn how to use if statements within for and while loops.
Exception Handling
Learn the try-except statements for properly handling errors in your programs.
Functions and Conditional Branching
Master how to use conditional branching inside functions to create reusable code.
This concludes our discussion of Python if statements. Use this knowledge to tackle more advanced programs. Mastering conditional branching will be a big step toward the next stage.