Week 5
Week 5
Week 5
GLOBAL VARIABLES,
MODULES, FILES
CS115
Introduction to Programming in Python
Week 5
▶ decomposition
▶ abstraction
▶ functions
▶ scope
2
THIS WEEK
▶ recursion
▶ global variables
▶ modules
▶ files
3
4
5
6
7
Computing Factorial
n! = n * (n - 1) * (n - 2) * … * 1
= n * (n - 1)!
factorial(0) = 1
factorial(n) = n * factorial(n-1)
8
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3)
9
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
10
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
11
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
12
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
13
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)
14
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)
= 3 * 2
15
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)
= 3 * 2
= 3 * 2
➢ See factorial_recursion.py
16
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)
= 4 * 3 * 2
= 4 * 6
= 24
17
Computing Factorial factorial(0) = 1
factorial(n) = n * factorial(n-1)
18
19
20
21
Fibonacci Numbers
➢ See fibonacci_recursion.py
22
Fibonacci Numbers
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89…
indices: 0 1 2 3 4 5 6 7 8 9 10 11
fib(0) = 0
fib(1) = 1
fib(index) = fib(index -1) + fib(index -2) if index >= 2
23
Fibonacci Numbers
24
Characteristics of Recursion
25
26
Think Recursively
▶ how to check if a string of characters is a palindrome, i.e., reads the same
forwards and backwards
○ Examples:
▶ “Madam”
▶ “Able was I, ere I saw Elba” – attributed to Napoleon
▶ First, convert the string to just characters, by stripping out punctuation, and
converting upper case to lower case
▶ Then
◦ Base case: a string of length 0 or 1 is a palindrome
◦ Recursive case:
◦ If first character matches last character, then is a palindrome if middle
section is a palindrome
27
Think Recursively
28
28
29
30
Global Variables
▶ Python also supports global variables (variables that are defined
outside functions)
▶ A global variable is visible from within all functions
▶ Any function that wants to update a global variable must
include a global declaration
▶ Variables that are assigned values/updated inside functions,
with the same name as global variables, will not be considered
global without the global declaration. They will be
considered as local variables.
▶ Warning: Global variables are not generally recommended. It
is a contradiction of modularity to have variables be accessible
in functions in which they are not used. Global variables can
cause unexpected results. 31
Global Variables - Example
Output: Output:
1 1
5 1
32
Modules
▶ Python contains a standard library that can be used to create
powerful programs.
▶ A library is a collection of code that is ready for you to use in
your program.
▶ A standard library is considered part of the language and must
be included with any Python system.
▶ Python’s standard library is organized into modules; each
module contains related functions.
▶ In addition to using the standard libraries, you can also create
your own modules, however it is rarely necessary to write your
own implementations for mathematical or string functions.
▶ Python Library 33
Using Modules - import
▶ Before using the functions contained in a module, you must first
import the module to your program
▶ Importing is done using an import statement
▶ Using the import statement, we can import specific functions within a
module or all functions contained in the module at once.
▶ Syntax:
from math import sqrt -> makes available only sqrt in math
from math import sqrt, sin, cos -> makes available specific functions listed
from math import * -> makes available all function in math module
import math -> makes available all functions in math module, when
ex: math.sqrt(25) 34
Creating our own Modules
35
Exercise
▶ Create a module (fitness_module.py) that stores fitness calculations.
Your module should define the following data and functions:
▪ MAX_RATE_CONSTANT (220)
▪ MAX_BMI (24)
▪ MIN_BMI (21)
▶ Create a script that inputs the age, height and weight from the user and
displays their fitness detail.
▶ fitness.py
36
Files
program
37
File Functions
Function Purpose
open(fileName, ’w’) Creates new a file for writing and returns the file object (file handle).
open(fileName, ’r’) Opens an existing file for reading and returns a file handle.
open(fileName, ’a’) Opens an existing file for appending and returns a file handle.
fh.read() Returns a string containing the contents of the file associated with the
file handle.
fh.readline() Returns the next line in the file associated with the file handle.
fh.readlines() Returns list, each element of which is one line of the file associated with
the file handle.
fh.write(s) Writes the string s to the end of the file associated with the file handle.
fh.writeLines(S) S is a sequence of strings, writes each element of S as a separate line to
the file associated with the file handle.
fh.close() Closes the file associated with the file handle.
38
Writing Data to a File
File Contents:
Melisa Aksoy
Sam Smith
39
Appending Data to a File
File Contents:
Melisa Aksoy
Sam Smith
Jane Doe
40
Reading Data from File – read()
41
Reading Lines from a File – readline()
# reading specific lines from a file - readline()
fileHandle = open('file1.txt', 'r')
for i in range(2):
line = fileHandle.readline()
print(line[:-1])
fileHandle.close()
Note:
▶ using the [:-1] syntax in the print method call stops the
print method from outputting the newline character from
the file data.
▶ We can also use the string strip() function, which removes
the leading and trailing whitespace characters and returns
the new string. 42
Reading Data from a File – for loop
43
Useful String Functions
45
Exercises (cont’d):
3. Write a program that reads two country data files, worldpop.txt
and worldarea.txt. Both files contain the same countries in the
same order. Write a file world_pop_density.txt that contains
country names and population densities (people per square km).
▶ world_country.py / worldpop.txt / worldarea.txt
46
Terms of Use
➢ This presentation was adapted from lecture materials provided in MIT Introduction to Computer Science
and Programming in Python.
➢ Licenced under terms of Creative Commons License.
47