4.1 — return vs. print, while statement, Modules

Assignment 1

  • Read the instruction pages
  • Ask questions on Ed Discussion — posts can be made anonymous
    • Make the post private when you want to include code
  • It is not enough that your solution passes all the given “public” tests
    • Make sure your solution will work for other values not given in the examples
    • Q1: use the blood type compatibility table to test your code with different values
    • Q2: Try different strings of lengths 1–10
    • Q3: For small n, you can use the given formula to verify your solution

What does this mystery function do?

Functions and return value None

Functions that do not have an explicit return statement, return a special value None.

The following 3 functions are equivalent because

  • Python implicitly returns None for a function that does not use a return statement
  • if the return statement is used without a value, None is returned.
1def greeting():
2 print("Welcome!")
1def greeting():
2 print("Welcome!")
3 return
1def greeting():
2 print("Welcome!")
3 return None

Function that prints

1def f(x):
2 result = x * x - x - 1
3 print(result)
4
5f(5) # No print here
6
7y = f(10) + 10 # TypeError

Less flexible to use; cannot be used with other expressions

Function that returns a value

1def f(x):
2 result = x * x - x - 1
3 return result
4
5print(f(5)) # print here
6
7y = f(10) + 10 # works

More flexible to use; can be used with other expressions

It is usually advisable to keep functions “pure” and do print(), input() outside the functions when possible.

Try the problem “Max of three numbers” on Ed Lessons.

Short Circuit Evaluation

The evaluation of a boolean expression with and and or stops as soon as the end result can be inferred.

For example, in the expression below evaluates to False no matter what not (x >= 1 or y == 3) evaluates to.

>>> 2 < 1 and not (x >= 1 or y == 3)
False

In general, for any expression with and operator:

left_operand and right_operand

if left_operand is False, Python does not evaluate right_operand.

Similarly, for any expression with or operator:

left_operand or right_operand

if left_operand is True, Python does not evaluate right_operand.

For example,

# Evaluates to True no matter what (x < 5) evaluates to
>>> 1 == 1 or (x < 5)
True

Why is Short Circuit Evaluation useful?

  • It can save time, e.g. when right_operand has a computationally expensive function call.
  • It can avoid unnecessary errors as show below.
1>>> x = 0
2>>> 1 / x < 0.5 # cannot divide a number by zero
3ZeroDivisionError: division by zero
4
5>>> x != 0 and 1 / x < 0.5
6False
7>>> x = 3
8>>> x != 0 and 1 / x < 0.5
9True

Common mistake when using logical operators

x == "a" or "b" # Incorrect
x == "a" or x == "b" # Correct
x == "a" and "b" # Incorrect
x == "a" and x == "b" # Correct

while statement

while statement is another way to repeatedly execute a block of code.

General format of a while loop:

Initialize variables so that condition is True while condition : code block update variables that affect condition

What while loop does:

  1. Evaluate the condition
  2. If condition evaluates to False, loop body is not executed.
  3. If condition evaluates to True, run the loop body (all indented lines of code)
    a) In loop body we perform some task, code block, and update variables that may change the condition value
    b) Go back to step 1

1# a program to compute sum of first N numbers
2N = 10
3
4total = 0
5
6i = 1 # Set value so that condition below is True
7while i <= N: # Check if condition is True
8 # main task of summing numbers:
9 total = total + i
10
11 # update i, affects value of condition i <= N
12 i = i + 1
13
14# print result outside the loop
15print(total)

It is a common mistake to forget updating the condition inside loop body.

See what happens when you remove/comment out the line i = i + 1 in the previous example.

The loop will never end — an infinite loop!

Augmented assignment statements

Augmented assignment is the combination, in a single statement, of a arithmetic operation and an assignment statement:

1x = 3
2y = 5
3
4x += 1 # same as: x = x + 1
5x += y # x = x + y
6x += x * y # x = x + x * y
7
8x -= 5 # x = x - 5
9
10x *= 2 # x = x * 2
  • Similarly, other operators exist: /=, //=, %=, **=.
  • These are very useful, especially when updating the condition in while loop.

Loops with indefinite number of steps

So far we have seen loops that work with fixed number of steps.

But while loop can be used for repeating code for unknown number of steps.

Write a program to keep asking for password until correct password is entered.

Assume that correct (secret) password is abcd1234.

1password = input("Enter password: ")
2
3while password != "abcd1234":
4 print("Incorrect password, try again!")
5
6 password = input("Enter password: ")
7
8# Below line executes only after the above loop ends,
9# i.e. when the correct password was entered.
10print("Login successful!")

for vs while loops

  • for loops are better when we want to go over a fixed sequence such as a string or a sequence of numbers
  • while loop is more flexible as it allows arbitrary conditions and number of steps. e.g. do something until user enters correct data

Importing modules

A module is a Python file (typically a .py file) containing function definitions, statements, etc.

Many modules such as math and random are already installed with Python.

Using import statement, we can use functions, variables etc. from a module in our program:

1import math
2
3# Call a function defined in a module using dot operator
4x = math.sqrt(16)
5print(x)
6
7y = math.sin(math.pi / 2)
8print(y)

Another way to import functions, variables from the module:

1from math import sqrt, sin, pi
2
3# Now, we can call sqrt and sin without the "math." prefix
4x = sqrt(16)
5print(x)
6
7y = sin(pi / 2)
8print(y)

Use help() function in Python Shell to see list of all function contained in math module:

>>> import math
>>> help(math) # will display a long doc, not showing here
>>> help(math.sqrt) # show help on a specific function
Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.

random module

In Python, we can generate random numbers using the random module.

The module provides us with a lot of different functions but for the moment we’ll focus on the following:

  • random() – It returns a random float value between 0.00.0 (inclusive) and 1.01.0 (exclusive)
  • randint(x, y) – It returns a random integer between x and y, both included.

Each time we execute these functions, we will get a different value, try it!

1import random
2
3print(random.random()) # 0.12826246225939641
4
5print(random.randint(1, 10)) # 9

Try the problem “Guessing Game” on Ed Lessons.