Python/Flow control

python flow control - if statement

kimble2 2024. 8. 3. 09:23
반응형

In Python, the if statement is a conditional statement used to execute code only if a certain condition is met. The code block associated with an if statement is executed only when the condition evaluates to True. The if statement can optionally include elif (else if) and else to handle multiple conditions.

Basic Structure

The basic structure of an if statement is as follows:

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

Example:

age = 20

if age >= 18:
    print("You are an adult.")  # Output: You are an adult.

if-else Statement

An else statement can follow an if statement to specify code to execute if the condition is False.

age = 15

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")  # Output: You are a minor.

 

if-elif-else Statement

The elif keyword allows for multiple conditions to be tested in sequence. You can use as many elif clauses as needed, followed optionally by an else clause.

 

score = 85

if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")  # Output: Grade B
elif score >= 70:
    print("Grade C")
else:
    print("Grade F")

 

Nested if Statements

An if statement can be nested inside another if statement.

num = 10

if num > 0:
    print("Positive number.")  # Output: Positive number.
    if num % 2 == 0:
        print("Even number.")  # Output: Even number.
else:
    print("Negative number.")

 

One-Line if Statement

Simple conditions and statements can be written on one line.

 

age = 20
message = "Adult." if age >= 18 else "Minor."
print(message)  # Output: Adult.

 

Using Comparison and Logical Operators

You can use comparison operators and logical operators to combine multiple conditions in an if statement.

  • Comparison Operators: ==, !=, <, >, <=, >=
  • Logical Operators: and, or, not
x = 10
y = 20

if x < y and x < 15:
    print("x is less than y and less than 15.")  # Output: x is less than y and less than 15.

if not (x > y):
    print("x is not greater than y.")  # Output: x is not greater than y.​

 
 

Truthy and Falsy Values

In Python, the following values are considered False in a conditional statement:

  • False
  • None
  • 0 (zero of any numeric type)
  • Empty sequences (such as "", [], ())
  • Empty collections (such as {}, set())

All other values are considered True. Therefore, you can use them directly in conditions.

 

value = ""

if value:
    print("There is a value.")
else:
    print("There is no value.")  # Output: There is no value.

 

The if statement is crucial for controlling the flow of a program, allowing different blocks of code to be executed or skipped based on conditions. This makes the program more flexible and responsive to varying inputs or states.

 

 

반응형

'Python > Flow control' 카테고리의 다른 글

python flow control - while  (0) 2024.08.10
python flow control - for loop  (0) 2024.08.03