Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Links | Search | Bio |

Guide to Python ( Version)


Chapter 3: Using Conditionals

Python conditionals provide a way to execute a statements or statements based on whether some condtion is met or not met.

Python if/else Conditional

The conditional statements (if, if/else, elif, while, etc.) allow you to test whether some condition is true or false. If the result of the test is true then the statement(s) after the : are executed.

Condition Operator
Equals ==
Not Equals !=
Less Than <
Less Than or Equql To <==
Greater Than >
Greater Than or Equal To >=

Figure 3-1: Python Conditions Operators

If the result is false the then statement(s) between the else { and } are executed. For example:

name1 = "Jim"
name2 = "D'arcy"
if name1 == name2:
  print("name1 (" + name1 + ") is the same as name2 (" + name2 + ")")
else:
  print("name1 (" + name1 + ") is not the same as name2 (" + name2 + ")")
Figure 3-2: Python if/else Statements
name1 (Jim) is not the same as name2 (D'arcy)
Figure 3-3: Python if/else Output

Python match Conditional

The match statement allows you to test whether some condition is met or not met. The match statement is similar to the switch statement in ther programming languages. If the parameter that is passed to the match statement is equal to any of the case statements then the statement(s) between that case: statement and break statement are executed. If the parameter does not match any of the case statements then the case_: statement(s) are executed. For example:

favTeam = 'yankees'

match favTeam:
    case 'red sox':
        print('Your favorite team is the Boston Red Sox.')
    case 'yankees':
        print('Your favorite team is the New York Yankees.')
    case 'blue jays':
        print('Your favorite team is the Toronto Blue Jays.')
    case _:
        print('Your favorite team is not the Yankees or the Red Sox or the Blue Jays.')
Figure 3-3: Python match Statement Using a String
Your favorite team is the New York Yankees.
Figure 3-4: Python match Using a String Output
secretNumber = 4
match (secretNumber):
    case 1:
        print("Your secret number is 1.")
    case 2:
        print("Your secret number is 2.")
    case 3:
        print("Your secret number is 3.")
    case _:
        print("Your secret number is not 1 or 2 or 3.")
Figure 3-6: Python match Using an Integer
Your secret number is not 1 or 2 or 3.
Figure 3-7: Python match Using an Integer Output

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2025 Jim Gerland