Python - Conditional Statements

python logo pixel art

Python uses conditional statements to control the flow of the program based on conditions.


To create a conditional statements, you should know:

  • Booleans
  • Relational Operators
  • Logical Operators
  • Identity Operators
  • Membership Operators

  • `if`

    if statement

    The `if` statements run the block of code when the condition is true.

    if condition:
      # steps...
    
    name = input("What's your name?")
    
    if name == 'batman':
      print('Hello, Bruce Wayne.')
    

    `if/else`

    if/else statement

    The `if/else` statements execute the `if` block when the condition is true; otherwise, the `else` block will be executed.

    if condition:
      # steps...
    else:
      # steps...
    
    name = input("What's your name?")
    
    if name == 'batman':
      print('Hello, Bruce Wayne.')
    else:
      print(f'Hello, {name}!')
    

    `if/elif`

    if/elif statement

    The `if/elif` statements let you test multiple conditions. When a condition is true, its block of code runs and the statement ends.

    if condition:
      # steps...
    elif condition:
      # steps...
    
    name = input("What's your name?")
    
    if name == 'batman':
      print('Hello, Bruce Wayne.')
    elif name == 'spider-man':
      print('Hello, Peter Parker.')
    else:
      print(f'Hello, {name}!')