Functions & Modules


CS 1109


June 28th, 2023

Administrative

  • Assignment 1 is due Friday at 9:00pm
  • Read Think Python: Ch. 3.1-8, 3.10-11 (skip 3.9 and 3.12) for tomorrow
  • Lab on functions tomorrow!

Algorithm Building Blocks

Algorithm Building Blocks

  • Predefined values & operations
  • Sequencing
  • Variables
  • Conditionals
  • Input/Output
  • Subroutines/Procedures
  • Repetition

Algorithm Building Blocks

  • Predefined values & operations
  • Sequencing
  • Variables
  • Conditionals
  • Input/Output
  • Subroutines/Procedures
  • Repetition

Functions

What is a function?

Examples of Functions

\[ f(x) = 2x + 1 \]

2x_plus_1.png

Examples of Functions

\[ f(x) = x^2 \]

x_squared.png

Functions in Programming

  • Similar to those in math:
    • Can take some input called parameters
    • Can return new values as output
  • A function is a "mini"-algorithm
    • Definition: A named sequence of statements that performs a computation.
    • Reusable!

Variables vs. Functions

Variable

A named value.

Function

A named algorithm or segment of code.

Examples of Python Functions

We have already seen a few:

  • print()
  • input()
  • int()
  • float()
  • type()

Function Calls

A function call is when you execute a function.

Example:

>>> int('42')
42
>>> type(3.14)
<class 'float'>

Defining Functions

"Hello, World!" Function

Function Definition

def hello_world():
		print("Hello, World!")

Function Call

>>> hello_world()
Hello, World!

Function Definition Structure

Function Definition Structure

Function Definition Structure

Function Definition Structure

Function Definition Structure

Function Definition Structure

Function Definition Facts

  • Functions can have any number of parameters, including zero!

    # This is a valid function!
    def greet():
    		print('Hi there!')
    
    # This is also a valid function!
    def greet_user(name):
    		print('Hi there, ' + name + '!')
    
  • Naming rules for variables apply for functions
    • Must start with a letter, then can use letters, digits, and _

return Statement

Format

return <EXPRESSION>

Evaluates the expression and sends the provided value to the caller

Example

def inc(x):
		return x + 1
>>> inc(3)
4
>>> inc(42.0)
43.0
>>> inc('x')
TypeError: can only concatenate str (not "int") to str

return ends the function

def inc2(x):
		ret = x + 1
		return ret
		ret = x + 1
		return ret

print(inc2(5))

Equivalent Function

def inc2_equiv(x):
		return x + 1

return ends the function

  • After executing a return statement, the function immediately terminates.
  • Any statements after a return statement are ignored.

return is optional

# This function has no `return` statement!
def greet():
		print('Hi there!')
  • return statements are optional
  • If absent, the function will end when there is no more code in the function body to execute

None

# demoGreet.py
def greet():
		print('Hi there!')

greet() # Correct call, `greet` doesn't return a value
x = greet() # `x` is now `None`
print(x)    # displays 'None'

None is a special value returned by functions without a return statement

How many times is 'Hi there!' printed?

# demoGreet.py
def greet():
		print('Hi there!')

greet() # Correct call, `greet` doesn't return a value
x = greet() # `x` is now `None`
print(x)    # displays 'None'

Twice! Once on line 5 and once on line 6, regardless of the assignment.

Fruitful vs. Void Functions

Fruitful Function

A function that returns a value.

Void Function

A function that only performs actions instead of returning a value.

Function Definition

  • Defines what function does
  • Declares parameters to function, if any
    • Listed between parentheses in function header, separated by commas

Function Call

  • A command to execute the function
  • Arguments are passed to the function as inputs
    • Listed between parentheses of function call, separated by commas
  • Can only be made after function is defined

Scope

Variable Scope

A variable's scope is the region of code where the variable is accessible.

Global Variables

Is this script valid?

# demoScope.py
name = 'Zach'

def greet():
		print('Hi ' + name)

greet()

Yes!

  • name is called a global variable as it is defined outside of a function
  • Global variables have global scope
    • Can be accessed anytime after the variable is defined

Local Variables

Parameters & variables defined inside of a function are only accessible in that function.

# demoScope2.py
def greet(name):
		greeting = 'Hi'
		print(greeting, name)

print(greeting) # NameError: name 'greeting' is not defined
print(name)     # NameError: name 'name' is not defined

Local vs. Global Variables

Local variables take precendence over global variables in function bodies.

# demoScope2.py
def greet(name):
		greeting = 'Hi'
		print(greeting, name)

greeting = 'Hello'
print('Zach') # displays 'Hi Zach', NOT 'Hello Zach'

Modules

Motivation

  • Problem: Programs can get large very quickly.
    • Need a way to split code across multiple files
  • Problem: I don't want to have to copy the same functions across multiple programs
    • Need a way to enable code reuse without copy-and-pasting
  • Problem: I want to incorporate someone else's code into my program
    • Example: Code for manipulating files, creating images, or to communicate over the Internet
    • Need a way to use someone else's code easily

Modules

  • Definition: A module is a file that provides functions and variables, usually according to a "theme".
    • Example: the math module provides common functions and variables for mathematical computations (e.g., sin, cos, pi)
  • Can be any file containing Python code, like our scripts!
  • Can import code from a module into your scripts

Using Modules

To use a module, you first have to import it!

>>> import math
>>> math.floor(1.9)
1
>>> math.sqrt(16)
4.0
>>> sqrt(16)
Traceback (most recent call last):
	File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
  • To access a function/variable you have to specify both the module name and the function/variable name
    • Example: math.floor
    • This is called dot notation

Simple Imports

Must fully specify function/variable using dot notation

>>> import math
>>> math.pi
3.141592653589793

Individual Imports

  • Can import specific functions/variables
  • Don't have to use dot notation!

    >>> from math import sqrt
    >>> sqrt(4)
    2.0
    >>> pi
    Traceback (most recent call last):
    	File "<stdin>", line 1, in <module>
    NameError: name 'pi' is not defined
    

Wildcard Imports

  • Import all function and variable names from a module
  • Dangerous: can conflict with your own function/variable names! Avoid if possible.

    >>> from math import *
    >>> sqrt(4)
    2.0
    >>> pi
    3.141592653589793
    

Module Help

Can learn more about a module (and associated functions/variables) by using the help function:

>>> import math
>>> help(math)
>>> help(math.ceil)

Using Your Own Modules

# min_max.py
def my_min(x, y):
		if x < y:
				return x
		else:
				return y

def my_max(x, y):
		if x >= y:
				return x
		else:
				return y
# min_max_calc.py
import min_max

def ask_for_int():
		num = int(input('Enter an integer: '))
		return num

# Get two `int`s from user
num1 = ask_for_int()
num2 = ask_for_int()

# Calculate the minimum and maximum
minimum = min_max.my_min(num1, num2)
maximum = min_max.my_max(num1, num2)

# Inform the user of the min/max
print('The minimum is:', minimum)
print('The maximum is:', maximum)

import Tips

import bar
  1. Python will first search for a built-in module named bar
    • Built-in Module Examples: math, sys, statistics
  2. Then search in folder script is in

    .
    └── cs1109/
    		├── lab1/
    		│   ├── bar.py
    		│   └── my_script1.py
    		└── lab2/
    				└── my_script2.py
    
    • my_script1.py can easily import bar; my_script2.py can't

What gets imported?

  • import only learns function headers
    • Function bodies are not executed
  • import does execute code outside of function bodies
# foo.py
def greet(name):
		print('Hi',name)

name = 'Anna'
greet(name)
>>> import foo
Hi Anna
>>> foo.name
'Anna'
>>> foo.greet('Greg')
Hi Greg

Modules vs. Scripts

Module

  • Use to provide functions, variables to other modules/scripts
  • Can import into REPL, script, or other module
  • After importing, you can reference module functions/variables
  • Generally does not have code in global space

Script

  • Use to write standalone programs
  • Intended to be run on the command line
  • Generally does have code in global space

Both are .py files, but how you use them is what matters!