\[ f(x) = 2x + 1 \]
\[ f(x) = x^2 \]
Variable
A named value.
Function
A named algorithm or segment of code.
We have already seen a few:
print()
input()
int()
float()
type()
A function call is when you execute a function.
Example:
>>> int('42')
42
>>> type(3.14)
<class 'float'>
Function Definition
def hello_world():
print("Hello, World!")
Function Call
>>> hello_world()
Hello, World!
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 + '!')
_
return
Statementreturn <EXPRESSION>
Evaluates the expression and sends the provided value to the caller
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 functiondef 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 functionreturn
statement, the function immediately terminates.return
statement are ignored.return
is optional# This function has no `return` statement!
def greet():
print('Hi there!')
return
statements are optionalNone
# 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
'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 Function
A function that returns a value.
Void Function
A function that only performs actions instead of returning a value.
Function Definition
Function Call
A variable's scope is the region of code where the variable is accessible.
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 functionParameters & 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 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'
math
module provides common functions and variables for mathematical
computations (e.g., sin
, cos
, pi
)import
code from a module into your scripts
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
math.floor
Must fully specify function/variable using dot notation
>>> import math
>>> math.pi
3.141592653589793
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
Dangerous: can conflict with your own function/variable names! Avoid if possible.
>>> from math import *
>>> sqrt(4)
2.0
>>> pi
3.141592653589793
Can learn more about a module (and associated functions/variables) by using the help
function:
>>> import math
>>> help(math)
>>> help(math.ceil)
# 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
Tipsimport bar
bar
math
, sys
, statistics
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'timport
only learns function headers
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
Module
import
into REPL, script, or other moduleScript
Both are .py
files, but how you use them is what matters!