1 of 40

Functions:

Modules and Imports

Jake Shoudy

Aug 31, 2021

CSCI 110 - Lecture 9

2 of 40

Announcements

3 of 40

Pre-class Surveys

Two surveys posted on Ed

Please take them 🙏 🙏 🙏

4 of 40

Reminder: HW2

Due Tonight at 11:59pm! (Late Days Allowed)

5 of 40

Reminder: Project 1: Part 2

Due Sunday (9/4) at 11:59pm! (No late days allowed!)

6 of 40

Reminder: Quiz 3

Friday! Meet in lab downstairs.

Will cover mostly while loops and strings

BE ON TIME

7 of 40

Reminder: Exam 1

2 weeks from today! (9/14)

8 of 40

Project 1: Part 1 Grades

  • Had a few technical issues on my end
  • Scores were temporarily added to canvas yesterday but were incorrect. Updated this morning to match autograder
  • No partial credit added. If you think you deserve more points come talk to me.
  • Recommended to use solution provided for part 2 if you are unsure about your part 1.

9 of 40

HW3

Will be released tomorrow!

A day late so will be due a day later (next Thursday)

10 of 40

Recap

11 of 40

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

12 of 40

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

13 of 40

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’

‘’

14 of 40

Escaping

\n - newline

\t - tab

\" - quotation mark

\' - apostrophe

\\ - backslash

15 of 40

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?"

16 of 40

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

17 of 40

Functions

18 of 40

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.

19 of 40

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

20 of 40

What are Functions?

Functions are lines of code grouped together. They have three things:

  1. name
  2. parameters/arguments
  3. return value

21 of 40

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)

22 of 40

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

23 of 40

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

24 of 40

Calling Functions

print('Hello, World!')

Function name

Argument

Parentheses

25 of 40

Calling Functions

float(100)

Function name

Argument

Parentheses

26 of 40

Calling Functions

num = float('2.25')

Function name

Argument

Parentheses

Return Value

27 of 40

Calling Functions

choice = input('Name?')

Function name

Argument

Parentheses

Return Value

28 of 40

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)

29 of 40

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

30 of 40

Importing Functions

31 of 40

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!

32 of 40

Import Statement

print(math.ceil(3.4))

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'math' is not defined

33 of 40

Import Statement

import math

print(math.ceil(3.4))

from math import ceil

print(ceil(3.4))

OR

34 of 40

Import Statement

All imports should be grouped together at the top of your file!

Good

Bad

35 of 40

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

https://docs.python.org/3/library/math.html

36 of 40

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

37 of 40

Flip a Coin

from random import randint

number = randint(1,2)

if number == 1:

print('Heads')

else:

print('Tails')

38 of 40

Let’s Code!

39 of 40

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

40 of 40

Questions?