Functions:
Modules and Imports
Jake Shoudy
Aug 31, 2021
CSCI 110 - Lecture 9
Announcements
Pre-class Surveys
Two surveys posted on Ed
Please take them 🙏 🙏 🙏
Reminder: HW2
Due Tonight at 11:59pm! (Late Days Allowed)
Reminder: Project 1: Part 2
Due Sunday (9/4) at 11:59pm! (No late days allowed!)
Reminder: Quiz 3
Friday! Meet in lab downstairs.
Will cover mostly while loops and strings
BE ON TIME
Reminder: Exam 1
2 weeks from today! (9/14)
Project 1: Part 1 Grades
HW3
Will be released tomorrow!
A day late so will be due a day later (next Thursday)
Recap
Review: Strings
len(s): returns length of string s
string[i]: access individual characters in string for index i
string[start:end]: substring - gets string from start to end, not including end
format: replaces {} with anything
upper/lower: changes string to all upper/lower case letters
strip: removes any leading or trailing spaces from a string
replace: finds instances of the first string and replaces it with the second
escaping: use \ to signify some special meaning
Review: Indexing
stage_name = 'childish gambino'
print(stage_name[1])
print(stage_name[4])
print(stage_name[-4])
print(stage_name[len(stage_name) - 1])
print(stage_name[20])
h
d
b
o
IndexError
Review: Slicing
name = 'Willy Wonka'
print(name[1:7])
print(name[:4])
print(name[4:])
print(name[-5:-1])
print(name[5:2])
‘illy W’
‘Will’
‘y Wonka’
‘Wonk’
‘’
Escaping
\n - newline
\t - tab
\" - quotation mark
\' - apostrophe
\\ - backslash
More String Practice!
thing = “ToES”.lower()
print("I have {} {} and a {} {}".format(22, thing, True, "heart"))
I have 22 toes and a True heart
print("My mother asked:\n\"Are you coming home for Labor day?\"")
My mother asked:
"Are you coming home for Labor day?"
Strings and while loops!
word = input(“Give me a word: ”)
index = 0
while index < len(word):
print(word[index])
index = index + 1
Give me a word: cool
c
o
o
l
Functions
Functions
function: performs specific action on a set of values
Takes inputs
Performs task on inputs
Optionally, gives output
Inputs and outputs of a function are values.
Parking Machine!
When leaving:
You feed the machine a ticket
Machine calculates how much time has passed
Shows you how much you have to pay
Example of a reusable machine that performs a specific task
What are Functions?
Functions are lines of code grouped together. They have three things:
Functions: Call
To call (run) a function, write its name followed by parentheses
int( )
input( )
print( )
"6"
"Name?"
"hello"
Inside parenthesis, pass in arguments (if function requires them to do its job)
Functions: Arguments
Values passed (provided) to a function for it to do its job
How to pass? Inside function’s parenthesis
Functions can take 0, 1, or many arguments
When function runs, a variable is created for each parameter with its value corresponding to what was passed in
Functions: Return
Values returned (provided) by a function after its job is done
How to use it? Store it in a variable or print it out
Functions can return 0 or 1 values
Calling Functions
print('Hello, World!')
Function name
Argument
Parentheses
Calling Functions
float(100)
Function name
Argument
Parentheses
Calling Functions
num = float('2.25')
Function name
Argument
Parentheses
Return Value
Calling Functions
choice = input('Name?')
Function name
Argument
Parentheses
Return Value
Common Confusions
call != define
call != print
return != print
print is just a function
print can still happen inside functions!
every function has a return value (or None)
Example: input()
answer = input(“How are you today?”)
Name:
input
Parameter:
string - “How are you today?”
It gets printed but not returned
Return:
string - whatever the user types
It gets returned but not printed
Importing Functions
Where do functions come from?
print(), int(), str()
built-in functions: packaged with Python, always available for use.
Can also import additional functions
import statement: loads module which provides a set of functions to use
Use already-written functions!
Import Statement
print(math.ceil(3.4))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
Import Statement
import math
print(math.ceil(3.4))
from math import ceil
print(ceil(3.4))
OR
Import Statement
All imports should be grouped together at the top of your file!
Good
Bad
import math
Access mathematical utilities
math.ceil(3.14) == 4
math.factorial(4) == 24
math.sqrt(25) == 5
math.cos(2*math.pi) == 1.0
randint()
randint(): function that takes two integers as inputs, returns a random integer between those two numbers, inclusive.
example: randint(0, 3) -> one of the integers 0, 1, 2, or 3 at random.
Included in random module
Flip a Coin
from random import randint
number = randint(1,2)
if number == 1:
print('Heads')
else:
print('Tails')
Let’s Code!
https://replit.com/team/csci110-01
Imported Functions
Review: Modules and Imports
What?
module: set of functions written and shared by another programmer
import statement: loads module into program to make its functions available
Why?
Use other people’s code, write code for others to use
Code organization - split project up into multiple files
Questions?