[파이썬] if-elif 구문의 의미

In Python programming, the if-elif statement is used to define conditions and execute different blocks of code based on these conditions. It stands for “if-else if,” and is used when we have multiple conditions to check.

The structure of an if-elif statement looks like this:

if condition1:
    # code block to be executed if condition1 is true
elif condition2:
    # code block to be executed if condition1 is false and condition2 is true
elif condition3:
    # code block to be executed if condition1 and condition2 are false and condition3 is true
else:
    # code block to be executed if none of the conditions above are true

Let’s break down the meaning of each part of the if-elif statement:

When executing an if-elif statement, Python checks the conditions in order from top to bottom. The first condition that evaluates to True will execute its associated code block, and the remaining conditions will be skipped.

Here’s an example to illustrate the usage and meaning of an if-elif statement:

age = 25

if age < 18:
    print("You are a minor.")
elif age >= 18 and age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

In this example, the code will output “You are an adult” since the age is neither less than 18 nor greater than or equal to 65.

Understanding the meaning of the if-elif statement is crucial for writing conditional code that can handle multiple possibilities and make decisions based on varying conditions. It allows for more flexibility and control in your Python programs.