2025年1月4日土曜日

Conditional Statements in Python

Conditional statements in Python control the flow of your program based on whether certain conditions are true or false. Here's a breakdown of the most common ones:

1. if Statement

  • Executes a block of code only if the condition is True.

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

    Example:

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

2. if-else Statement

  • Executes one block of code if the condition is True, and another block if it's False.

    Python
    if condition:
        # Code to execute if condition is True
    else:
        # Code to execute if condition is False
    

    Example:

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

3. if-elif-else Statement

  • Checks multiple conditions in sequence.

  • Executes the block corresponding to the first True condition.

  • If no conditions are True, executes the else block.

    Python
    if condition1:
        # Code to execute if condition1 is True
    elif condition2:
        # Code to execute if condition2 is True
    elif condition3:
        # Code to execute if condition3 is True
    else:
        # Code to execute if none of the conditions are True
    

    Example:

    コード スニペット
    grade = 85
    
    if grade >= 90:
        print("Excellent!")
    elif grade >= 80:
        print("Good job!")
    elif grade >= 70:
        print("Satisfactory.")
    else:
        print("Needs improvement.")
    

Key Considerations:

  • Indentation: Python relies heavily on indentation to define code blocks within conditional statements. Use consistent spacing (usually 4 spaces) for proper execution.
  • Comparison Operators: Familiarize yourself with comparison operators like == (equal to), != (not equal to), >, <, >=, <=.
  • Logical Operators: Combine multiple conditions using and, or, and not to create more complex expressions.

Example with Logical Operators:

Python
age = 25
has_driver_license = True

if age >= 18 and has_driver_license:
    print("You are eligible to rent a car.")

By mastering these conditional statements, you'll be able to write more dynamic and responsive Python programs that make decisions based on various inputs and conditions.

0 件のコメント:

コメントを投稿