If/Else

Estimated Time: 30 minutes


Conditional statements

A conditional statement runs code based on a specific condition.

In Python, the syntax uses the keyword if, a condition followed by a colon :, and then an indented block of code to run.

if response == "yes":
	print("Proceeding...")

The print only runs if the value of the variable response is equal to "yes"

In this example, the condition is response == "yes" and the code block is print("Proceeding...").

The code block ends when you stop indenting.

In the following example, "Goodbye" is always printed, no matter what the response is. It’s outside of the code block, because it’s no longer indented.

response = input("Type 'yes' to proceed")
if response == "yes":
	print("Proceeding...") # only runs if response is equal to "yes"

print("Goodbye")         # runs no matter what

Practice

If-Else

Sometimes we want to do one thing if a boolean expression is true, and something else if it is false. In those cases, we can write an if-else statement.

Take a look at the example below. It prints a different message based on whether x is even or odd.

if x % 2 == 0:
    print('x is even')
else:
    print('x is odd')

We want to check if a given number x is even or odd. The % operator is called ‘modulo’ and it returns the remainder after division. If the remainder is 0 when x is divided by 2, then x is even. The flow control diagram looks like this:

2%201%20Simple%20decisions%20efbfa340f5df47bd9059c5d369f5793d/Untitled%201.png

The boolean expression x % 2 == 0 checks to see if the remainder of x divided by 2 is equal to 0. If this is true, then the first indented statement (called a branch) gets executed and the program prints "x is even". If the boolean expression is false, then the branch after theelse gets executed instead and the program prints "x is odd".

When writing conditional statements, you must pay attention to indentation. You must indent after an if statement, maintain the indent as long as you want to be in the if block, then reduce the indent when done with the if block. Also, don't forget to add the : after the condition, and another : after the else if you have one.

Practice

2%201%20Simple%20decisions%20efbfa340f5df47bd9059c5d369f5793d/Screen_Shot_2021-07-27_at_5.46.48_PM.png

A sample run of the code should look like this:

2%201%20Simple%20decisions%20efbfa340f5df47bd9059c5d369f5793d/Untitled%202.png