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 | >= |
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 + ")")
if/else
Statementsname1 (Jim) is not the same as name2 (D'arcy)
if/else
OutputPython 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.')
match
Statement Using a StringYour favorite team is the New York Yankees.
match
Using a String OutputsecretNumber = 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.")
match
Using an IntegerYour secret number is not 1 or 2 or 3.
match
Using an Integer Output