目次
1. Introduction
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’sif 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.Ad
2. Basic Syntax of if Statements
Python’sif 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’sif statement is as follows.if condition:
code_to_executeImportance of Indentation
In Python, code hierarchy is expressed using indentation. When the condition of anif statement is true, the code to be executed must be indented one level. Example: Correct Indentationif 10 > 5:
print("10 is greater than 5")Example: Incorrect Indentationif 10 > 5:
print("10 is greater than 5") # errorIn Python, incorrect indentation causes errors, so you need to be careful.Condition Expressions
The condition expression used in anif 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’sif 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 returnTrue 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 |
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 |
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
Inif statements, you can handle complex conditions by combining comparison and logical operators. Example: Combining Multiple Conditionsage = 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.Ad
4. if-else statement
In addition to the basicif 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 falseExample usage
Below is a simple example using anif-else statement. Example: Using an if-else statementx = 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
Theif-else statement is frequently used for dynamic processing based on user input and conditions. Example: Conditional branching based on user inputnumber = 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 onlyif 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 trueelif is short for “else if” and is used to check multiple conditions in order.Example usage
Below is a simple example using theif-elif-else statement. Example: Conditional branching based on numeric rangesscore = 85
if score >= 90:
print("Rating: A")
elif score >= 80:
print("Rating: B")
elif score >= 70:
print("Rating: C")
else:
print("Rating: D")In this example, different messages are displayed depending on the value of score.Importance of elif
Usingelif causes conditions to be evaluated sequentially, allowing efficient processing even when multiple conditions overlap. Example: Condition prioritytemperature = 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 omittedage = 20
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")Ad
6. Nested if statements
When conditions become more complex, you can nestif statements. This chapter explains how to write nested if statements and the points to consider.Basic structure of nested if statements
The structure of nestedif statements is as follows.if condition1:
if condition2:
process when both condition1 and condition2 are trueExample usage
The following is an example using nestedif statements. Example: Combining two conditionsage = 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 nestingage = 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")Ad
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 value2conditionisTrue,value1is returned.conditionisFalse,value2is returned.
Examples
Example: Number Classificationx = 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 Determinationa, 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 Operatorx = 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-elsestatement improves readability. - Overusing the ternary operator can reduce code readability, so aim to use it only in appropriate situations.
Ad
8. Precautions for if Statements
Python’sif 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 Nonex = None
if not x:
print("x is None")Example: Evaluation of Empty Valuesitems = []
if not items:
print("The list is empty")is and == Differences
==compares value equality.iscompares object identity (whether they are the same object in memory).
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 Parenthesesx = 10
y = 5
if (x > 5 and y < 10) or x == 10:
print("Condition is met")
Ad
9. Summary
In this series, we have learned the basics to advanced topics of Python’sif statements. In this chapter, we will review what we have covered so far and organize the key points.Fundamentals of Python if Statements
ifstatements execute specific code only when the condition isTrue.- In Python, indentation determines code structure, so proper indentation is essential.
if condition:
code_to_executeExtending Conditional Branching
- Using
if-elsestatements allows you to specify handling for when the condition isFalse. - With
if-elif-elsestatements, you can efficiently handle multiple conditions.
score = 75
if score >= 90:
print("Rating: A")
elif score >= 75:
print("Rating: B")
else:
print("Rating: C")Handling Complex Conditions
- By combining comparison and logical operators, you can express more complex conditions.
- Using nested
ifstatements allows you to handle hierarchical conditions.
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-elsestatement.
result = "Pass" if score >= 60 else "Fail"Things to Note
- Empty values and
Noneare treated asFalse. - Understand the difference between
isand==and use them appropriately. - When conditions become complex, using parentheses to clarify precedence is important.
Next Steps
Python’sif 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
ifstatements withinforandwhileloops.
- Exception Handling
- Learn the
try-exceptstatements for properly handling errors in your programs.
- Functions and Conditional Branching
- Master how to use conditional branching inside functions to create reusable code.
if statements. Use this knowledge to tackle more advanced programs. Mastering conditional branching will be a big step toward the next stage.



