Conditionals & Loops

Tips for navigating the slides:
  • Press O or Escape for overview mode.
  • Visit this link for a nice printable version
  • Press the copy icon on the upper right of code blocks to copy the code

Class outline:

  • Review
  • Booleans
  • Conditionals
  • Loops intro

Review

Defining functions

We define functions in Python with a def statement.


                    def <name>(<parameters>):
                        return <return expression>
                    

Example:


                        def add(num1, num2):             # ← Function signature
                            sum = num1 + num2            # ← Function body
                            return sum                   # ← Function body
                        

Once defined, we can call it:


                    add(2, 2)
                    add(18, 69)
                    

Function arguments

We can pass in any expressions as arguments.


                    def add(num1, num2):
                        return num1 + num2
                    

                    x = 1
                    y = 2
                    add(x, y)
                    

                    x = 3
                    add(x * x, x + x)
                    

Return values

The return keyword returns a value to whoever calls the function (and exits the function).


                    def add(num1, num2):
                        return num1 + num2

                    sum = add(2, 4)
                    

Namespaces

Python uses the concept of namespaces to organize the symbolic names assigned to objects, like variables and functions. Namespaces help to avoid name conflicts.
Python has 4 levels of namespaces:

Built-in Contains the names of all of Python’s built-in objects (ex, functions like print() and pow())
Global Contains any names defined at the level of the main program (ie, variable & function names that are NOT indented)
Enclosing When functions are nested, contains names defined inside a parent function (ie, variabl & function names that are indented)
Local Contains names defined inside a function (ie, variable names that are indented)

Example: Global vs Local names

In practice, we mostly care about whether a name is global or local.

Global screenshot showing global env
Local screenshot showing

Side effects

A side effect is when something happens as a result of calling a function besides just returning a value.

The most common side effect is logging to the console, via the built-in print() function.


                    print(-2)
                    

A similar side effect is writing to a file:


                    f = open('songs.txt', 'w')
                    f.write("Dancing On My Own, Robyn")
                    f.close()
                    

Side effects vs. Return values


                    def square_num1(number):
                        return pow(number, 2)
                    

                    def square_num2(number):
                        print(number ** 2)
                    

Default arguments

In the function signature, a parameter can specify a default value. If that argument isn't passed in, the default value is used instead.


                    def calculate_dog_age(human_years, multiplier = 7):
                        return human_years * multiplier
                    

These two lines of code have the same result:


                    calculate_dog_age(3)
                    calculate_dog_age(3, 7)
                    

Default arguments can be overriden:


                    calculate_dog_age(3, 6)
                    

Multiple return values

A function can specify multiple return values, separated by commas.


                    def divide_exact(n, d):
                        quotient = n // d
                        remainder = n % d
                        return quotient, remainder
                    

Any code that calls that function must also "unpack it" using commas:


                    q, r = divide_exact(618, 10)
                    

Practice exercise review

Let's review the homework from last week together!

(Note: we did Class2Ex2TemperatureConverter together in class)

Boolean expressions

Booleans

A Boolean value is either True or False and is used frequently in computer programs.

Google Maps uses a boolean to decide whether to avoid highways in driving directions:


                    avoid_highways = True
                    

Twitter uses a boolean to remember where the user allows personalized ads:


                    personalized_ads = False
                    

Boolean expressions

An expression can evaluate to a Boolean. Most Boolean expressions use either comparison or logical operators.


An expression with a comparison operator:


                    passed_class = grade > 65
                    

An expression with a logical operator:


                    wear_jacket = is_raining or is_windy
                    

Let's try it in Replit . Create a new Python 3 Repl.

Comparison operators

Operator Meaning True expressions
== Equality 32 == 32, "foo" == "foo"
!= Inequality 30 != 32, "foo" != "bar"
> Greater than 60 >= 32
>=Greater than or equal 60 >= 32 , 32 >= 32
< Less than 20 < 32
<= Less than or equal 20 <= 32, 32 <= 32

Comparison operators

⚠️ Common mistake: Do not confuse = (the assignment operator) with == (the equality operator).


                            x = y
                        

is very different from


                            x == y
                        

Logical operators

OperatorTrue expressions Meaning
and 4 > 0 and -2 < 0 True if both conditions are true; otherwise evaluates to False. Same as && in other languages.
or 4 > 0 or -2 > 0 True if either condition is true; evaluates to False only if both are false. Same as || in other languages.
not not (5 == 0) True if condition is false; evaluates to False if condition is true. Same as ! in other languages.

W3Schools has a handy Python operators reference

Logical operators

You might recognize logical operators from Advanced Search tools, like in Google Advanced Search

Screenshot of Google advanced search

Compound booleans

When combining multiple operators in a single expression, use parentheses to group:


                    may_have_mobility_issues = (age >= 0 and age < 2)  or age > 90
                    

Boolean expressions in functions

A function can use a Boolean expression to return a result based on the values of the parameters.


                    def passed_class(grade):
                        return grade > 65
                    

                    def should_wear_jacket(is_rainy, is_windy):
                        return is_rainy or is_windy
                    

Exercise: Booleans

Open Class3Ex1Booleans in Replit and click "Fork Repl" to create your own copy

We'll do the first question together; the rest will be homework for the next class.

Conditionals

Conditional statements

A conditional statement gives you a way to execute a different set of code statements based on whether certain conditions are true or false.


                    if <condition>:
                        <statement>
                        <statement>
                        ...
                    

A simple conditional:


                    clothing = "shirt"

                    if temperature < 32:
                        clothing = "jacket"
                    

In what situations will clothing be assigned to "jacket"?

The else statement

A conditional can include an else statement to specify code to execute when the if condition is False


                    if <condition>:
                        <statement>
                    else <condition>:
                        <statement>
                    

                    if temperature < 0:
                        clothing = "snowsuit"
                    else:
                        clothing = "jacket"
                    

The elif statement

When you have more than 1 condition you want to check, you can use elif statements to check other conditions. Works kind of like a "choose your own adventure" book!


                    if <condition>:
                        <statement>
                        ...
                    elif <condition>:
                        <statement>
                        ...
                    elif <condition>:
                        <statement>
                        ...
                    

                    clothing = "shirt"

                    if temperature < 0:
                        clothing = "snowsuit"
                    elif temperature < 32:
                        clothing = "jacket"
                    

elif + else

else can be used along with 1 or more elif statements to specify code to execute as a last resort, if no previous conditions are true.


                    if <condition>:
                        <statement>
                        ...
                    elif <condition>:
                        <statement>
                        ...
                    else <condition>:
                        <statement>
                        ...
                    

                    if temperature < 0:
                        clothing = "snowsuit"
                    elif temperature < 32:
                        clothing = "jacket"
                    else:
                        clothing = "shirt"
                    

Understanding conditionals


                    clothing = "shirt"
                    if temperature < 0:
                        clothing = "snowsuit"
                    elif temperature < 32:
                        clothing = "jacket"
                    else:
                        clothing = "shirt"
                    
temperatureclothing
-50snowsuit
-1snowsuit
0jacket
1jacket
31jacket
32shirt
50shirt

Conditional statements summary


                    if num < 0:
                        sign = "negative"
                    elif num > 0:
                        sign = "positive"
                    else:
                        sign = "neutral"
                    

Syntax tips:

  • Always start with if clause.
  • Zero or more elif clauses.
  • Zero or one else clause, always at the end.

Conditional evaluation order

How Python interprets a conditional:

  • Evaluate the condition in the first clause.
  • If it's true, execute the suite of statements underneath and skip the remaining caluses.
  • Otherwise, continue to the next clause and repeat.
Screenshot of a conditional statement Screenshot of a conditional statement

Conditionals in functions

It's common for a conditional to be based on the value of the parameters to a function.


                    def get_number_sign(num):
                        if num < 0:
                            sign = "negative"
                        elif num > 0:
                            sign = "positive"
                        else:
                            sign = "neutral"
                        return sign
                    

                    get_number_sign(50)  # "positive"
                    get_number_sign(-1)  # "negative"
                    get_number_sign(0)   # "neutral"
                    

Returns inside conditionals

A branch of a conditional can end in a return, which exits the function entirely.


                    def get_number_sign(num):
                        if num < 0:
                            return "negative"
                        elif num > 0:
                            return "positive"
                        else:
                            return "neutral"
                    

                    get_number_sign(50)  # "positive"
                    get_number_sign(-1)  # "negative"
                    get_number_sign(0)   # "neutral"
                    

Exercise: Conditionals

Class3Ex2Conditionals

We'll do the first question together; the rest will be homework for the next class

Loops

Why loops?

Sometimes we need to do the same thing over and over, with different data.

Consider the following code...


                    print(9 * 1)
                    print(9 * 2)
                    print(9 * 3)
                    print(9 * 4)
                    print(9 * 5)
                    

This code is repetitive and variable, but the variability is sequential - it just adds one to the right-hand side number each time. In English, we could describe this as "print out the first 5 multiples of 9".

We can simplify this code with a loop!

Types of loops

Python has 2 types of loops:

  • While: Runs code as long as a specified condition is True (unknown number of times)
  • For: Runs code for a specified set of values (known number of times)

While loops

While loops

The while loop syntax:


                    while <condition>:
                        <statement>
                        <statement>
                    

As long as the condition is true, the statements below it are executed.


                    multiplier = 1
                    while multiplier <= 5:
                        print(9 * multiplier)
                        multiplier += 1
                    

The code is significantly shorter, and it can easily be extended to loop for more or less iterations.

Using a counter variable

We need to tell a While loop when to stop, otherwise it might keep running forever!

It's common to use a counter variable whose job is keeping track of the number of times the loop has run.


                    total = 0
                    counter = 0
                    while counter < 5:
                      total += pow(2, 1)
                      counter += 1
                    

Special assignment operators

What's this += thing?

  • One of several "special" assignment operators
  • Does math on an existing variable value and assigns the result to that variable at the same time
  • A handy shortcut counter += 1 does the same thing as counter = counter + 1

Can also subtract -=, multiply *=, divide /= and assign the result

See the full list of special assignment operators on W3Schools

Using a counter variable

How many times will this loop run?


                    total = 0
                    counter = 0
                    while counter < 5:
                      total += pow(2, 1)
                      counter += 1
                    

The loop runs while counter is 0, 1, 2, 3 and 4, so 5 times

Changing a while loop #1

You can change the initial values of the variables used in the condition:


                    multiplier = 3
                    while multiplier <= 5:
                        print(9 * multiplier)
                        multiplier += 1
                    
  • What will be the first thing displayed? 27
  • What will be the last thing displayed? 45
  • How many iterations? 3 (for values of 3, 4, 5)

Changing a while loop #2

You can change the condition:


                    multiplier = 3
                    while multiplier <= 10:
                        print(9 * multiplier)
                        multiplier += 1
                    
  • What will be the first thing displayed? 27
  • What will be the last thing displayed? 90
  • How many iterations? 8 (for values of 3, 4, 5, 6, 7, 8, 9, 10)

Changing a while loop #3

You can change how much the values change between iterations:


                    multiplier = 3
                    while multiplier <= 10:
                        print(9 * multiplier)
                        multiplier += 2
                    
  • What will be the first thing displayed? 27
  • What will be the last thing displayed? 81
  • How many iterations? 4 (for values of 3, 5, 7, 9)

Beware infinite loops

Uh oh..


                    counter = 1
                    while counter < 5:
                        total += pow(2, counter)
                    

What one line of code would fix this?
counter += 1


                    counter = 6
                    while counter > 5:
                      total += pow(2, counter)
                      counter += 1
                    

How do we save this code?
Intentions are unclear! Change the initial value and condition?

The break statement

To prematurely exit a loop, use the break statement:


                    counter = 100
                    while counter < 200:
                        if counter % 7 == 0:
                            first_multiple = counter
                            break
                        counter += 1
                    

Loops in functions

A loop in a function will commonly use a parameter to determine some aspect of its repetition.


                    def sum_up_squares(start, end):
                        counter = start
                        total = 0
                        while counter <= end:
                          total += pow(counter, 2)
                          counter += 1
                        return total

                    sum_up_squares(1, 5)
                    

Exercise: While loops

Class3Ex3WhileLoops

We'll do the first question together; the rest will be homework for the next class

Homework!

Finish the rest of the questions in each exercise - we'll review in the next class

How is it going?

Please fill out the feedback form to let me know how I can improve the class!

https://forms.gle/iENMqYvdahR9AP5UA