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 - 13 print(result)45f(5) # No print here67y = 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 - 13 return result45print(f(5)) # print here67y = 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 = 02>>> 1 / x < 0.5 # cannot divide a number by zero3ZeroDivisionError: division by zero45>>> x != 0 and 1 / x < 0.56False7>>> x = 38>>> x != 0 and 1 / x < 0.59True
Common mistake when using logical operators
x == "a" or "b" # Incorrectx == "a" or x == "b" # Correct
x == "a" and "b" # Incorrectx == "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:
- Evaluate the
condition
- If
condition
evaluates to False, loop body is not executed. - 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 thecondition
value
b) Go back to step 1
1# a program to compute sum of first N numbers2N = 1034total = 056i = 1 # Set value so that condition below is True7while i <= N: # Check if condition is True8 # main task of summing numbers:9 total = total + i1011 # update i, affects value of condition i <= N12 i = i + 11314# print result outside the loop15print(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 = 32y = 534x += 1 # same as: x = x + 15x += y # x = x + y6x += x * y # x = x + x * y78x -= 5 # x = x - 5910x *= 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: ")23while password != "abcd1234":4 print("Incorrect password, try again!")56 password = input("Enter password: ")78# 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 math23# Call a function defined in a module using dot operator4x = math.sqrt(16)5print(x)67y = math.sin(math.pi / 2)8print(y)
Another way to import functions, variables from the module:
1from math import sqrt, sin, pi23# Now, we can call sqrt and sin without the "math." prefix4x = sqrt(16)5print(x)67y = 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 functionHelp 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.0 (inclusive) and 1.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 random23print(random.random()) # 0.1282624622593964145print(random.randint(1, 10)) # 9
Try the problem “Guessing Game” on Ed Lessons.