2.5. Lecture 4: Python 2

Before this class you should:

  • Read Think Python:

    • Chapter 5: Conditionals and recursion;

    • Chapter 6: Fruitful functions; and

    • Chapter 7: Iteration

Before next class you should:

  • Read Think Python:

    • Chapter 8: Strings;

    • Chapter 10: Lists;

    • Chapter 11: Dictionaries; and

    • Chapter 12: Tuples

Note taker : Ricardo Murray

Professor: Graham Taylor

Source: Content adapted from Think Python 2e by Allen B. Downey

2.5.1. Floor Division and Modulus

Floor division (//) rounds the result down to the nearest whole number. Modulus (%) returns the remainder of a division.

Example:

minutes = 105
hours = minutes // 60  # returns hours = 1
remainder = minutes % 60 # returns remainder = 45

2.5.2. Boolean Expressions

Recall expressions from last lecture. Expressions evaluate something and in Python, their output is printed. Boolean expressions are conditions that return either True or False.

5 == 5  # Returns True
5 == 6  # Returns False

Note: True and False are special values in python, they belong to the type bool; they are not strings.

x!= y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x <= y # x is less than or equal to y
x >= y # x is greater than or equal to y

2.5.3. Logical Operators

Python includes several logical operators: and, or, not. Evaluates an expression and return True or False based on expressions.

Example:

x = 5
print(x > 0 and x < 10)  # Returns True

Note: Operands of the logical operators should be of boolean type, but Python is not very strict. Any nonzero number is interpreted as True, thus zero is interpreted as False. Using numbers directly in logical operations without explicit comparison can lead to unintended behaviors, especially when the logical interpretation of the number (as True or False) was not intended by the programmer. This approach should be avoided as it may result in code bugs.

2.5.4. Conditional Execution

Use if statements to execute code based on conditions.

x = 4
if x > 0:
    print('x is positive')

2.5.5. Chained and Nested Conditionals

Chained conditionals use elif for multiple conditions, while nested conditionals are conditionals within conditionals.

2.5.6. Recursion

Functions can call themselves, which is useful for tasks that can be defined in terms of themselves. Without the base case in a recursive function, it would keep calling itself endlessly, leading to stack overflow error. The base case acts as a condition under which the function stops calling itself and begins to return.

See the basic countdown function below which includes a base case:

def countdown(n):
    if n <= 0:
        print('Blastoff!')
    else:
        countdown(n-1)

In this example, n <= 0 is the base case. When n is less than or equal to zero, the function stops calling itself and prints “Blastoff!”. This prevents it from running indefinitely.

2.5.7. Infinite Recursion and Debugging

Avoid infinite recursion as it causes programs to run indefinitely. Always ensure there is a base case that stops recursion.

2.5.8. Keyboard Input

input() allows user input and can be used with a prompt.

name = input('What is your name?\n')

2.5.9. Boolean Functions

Functions that return a boolean value are often used to simplify complex checks.

def is_divisible(x, y):
    return x % y == 0

2.5.10. More on Recursion

Recursion can often simplify the coding of certain problems, such as calculating factorials.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

2.5.11. Reassignment and Updating Variables

Variables can be reassigned and updated. Updates typically modify the existing value of a variable.

x = 5
x = 7  # Reassigns x to 7
x = x + 1  # Updates x to 8

2.5.12. The while Statement

while loops repeat as long as a condition is True. An improperly handled infinite loop occurs when a while loop lacks an effective condition to break out of the loop, causing it to run indefinitely. Here’s an example:

n = 5
while True:  # Loop has no exit condition
    print(n)
    n = n - 1
    if n == -1:  # This condition does not stop the loop
        n = 5  # Resets n to 5, causing an infinite loop

In this example, the while True creates a loop that runs indefinitely. Even though the value of n changes, the condition to exit the loop is handled incorrectly, causing n to reset to 5 and never allowing the loop to terminate.

This can be fixed by simply setting a clear and reachable exit condition as shown below:

n = 5
while n >= 0:  # Loop continues as long as n is non-negative
    print(n)
    n = n - 1  # Decrements n

2.5.13. Break and Square Roots

break is used to exit a loop prematurely. Newton’s method is an example of using loops for numerical computation.

a = 4
x = 3
while True:
    y = (x + a/x) / 2
    if abs(y-x) < 0.0000001:
        break
    x = y

For more details, review the lecture slides and additional readings.