Outline

Conditional Statements

Conditional statements in Python are similar to other languages and offers the same features. You can also do conditional expressions, called ternary operators, to quickly test a condition instead of using a multi line if statement.

Read up on the official documentation on compound statements

Compound statements include the if statement, while statement for statement which implement traditional control flow. try and with statements are included as well as Function and Class definitions.

Indentation = Python

if <expression>:        # clause header - begins
    <do something here>         # clause suite - a group of statements controlled by a clause.
    <do something here>
    ...
    <do something here>
<next statement after the if block>

Python refers to this indentation, or compound statement, as a clause. A clause consists of a header and a 'suite'. The suite can be one or more semicolon-separated simple statements on the same line as the header, following the header's colon, or it can be one or more indented statements on subsequent lines. If you are going to nest compound statements then you'll use the indented statements on subsequent lines format.

if test1: if test 2: print(x)

If the test is false, all of the statements in the suite are skipped and the suite of the else clause, if present, is executed. Let's start out with a fun example of a Magic 8 Ball app. Start by creating a new file magic8ball.py . We'll start by importing sys and random then set up our variables for looping until the user wants to exit. Use indentation to lay out the responses, while loop, and if block.

import sys
import random

ans = True
response = [
    'It is certain',
    'Outlook good',
    'You may rely on it',
    'Ask again later',
    'Concentrate and ask again',
    'Reply hazy, try again',
    'My reply is no',
    'My sources say no'
]

while ans:
    question = input(
        'Ask the magic 8 ball a question: (press enter to quit) '
        )

    answers = random.randint(0, 7)

    if question == "":
        ans = False
    else:
        print(response[answers])

Then we can run it in the interpreter to check and see if things work.

$ python magic8ball.py
Ask the magic 8 ball a question: (press enter to quit) Will it rain today?
You may rely on it
Ask the magic 8 ball a question: (press enter to quit) Should I program this in Python?
Ask again later
Ask the magic 8 ball a question: (press enter to quit) 
$

Else If

Python supports the option of an else if statement by using elif. Here's a simple example of how it can be used

testNum = 9.5 

if testNum == 0:
    print('Found Zero')
elif testNum > 0:
    print('Positive Number')
else:
    print('Negative Number')

Ternary Operators

Conditional expressions are known in other languages as in-line statements . It allows us to quickly check the condition and operate on it. You may have seen some examples of this when we were formatting strings using string interpolation. Let's look at an example of this:

gender = "Female"

print(f'Congrats on your new baby {"boy" if gender == "Male" else "girl"}!')

# The values can be truthy as well
# male = 1, female = 0
gender = 1
print(f'Congrats on your new baby {"boy" if gender else "girl"}!')
# Congrats on your new baby boy!

gender = 0
print(f'Congrats on your new baby {"boy" if gender else "girl"}!')
# Congrats on your new baby girl!

While Loop

Get to know the while statement from the Python Docs

The while statement is used for repeated execution as long as an expression is true. It's similar to the if condition, even allowing you to use an else statement. While loops run untile the condition is met.

count = 0
while (count < 5):
    count = count + 1
    print("inner loop")
else:
    print('in the else statement')

# Output
inner loop
inner loop
inner loop
inner loop
inner loop
in the else statement

For Loop

Get to know the for statement from the Python Docs and the examples below.

Used to iterate over the elements of a sequence (string, tuple or list) or any other iterable object. At the construction of the loop we know the number of times it's going to run.

The basic structure of the for loop:

heroes = ['Superman', 'Batman', 'Flash']
for hero in heroes:
    print(hero.upper())

# output
# SUPERMAN
# BATMAN
# FLASH
 

I finished! On to the next chapter