if, else, and elif Statements

1. If-else branches (general)

In many circumstances when we write a program, we need the ability to check conditions and change the behavior of the program accordingly. 

Selection statements or conditional statements, give us this ability.

Example: Let's look through the following code:

if my_class_average > 1:
print("I passed the class! Hooray!")
else:
print("Bummer! I will have to re-take this class!")

Consider another code fragment:

x = int(input("Enter an integer value:"))
y = int(input("Enter another integer value:"))
if x > y:
a = x
if x < y:
a = y
else:print("They are equal!")

Consider another code fragment:

x = int(input("Enter an integer value:"))
y = int(input("Enter another integer value:"))
if x > y: //conditions (evaluated to a Boolean value: True or False)
a = x
if x < y: //conditions (evaluated to a Boolean value: True or False)
a = y
else:
print("They are equal!")

If we type the following commands in the Python shell, we will get the responses in purple:

>>>2==2
True
>>>
2<3
True
>>>
3>7
False
>>>5>9or2<3
True

Source: Natalia Novak, https://academicworks.cuny.edu/bx_oers/34/
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.