Introduction to Functions in Python
Hugo Bowne-Anderson
Instructor
Define functions without parameters
Define functions with one parameter
Define functions that return a value
Later: multiple arguments, multiple return values
str()
x = str(5)
print(x)
'5'
print(type(x))
<class 'str'>
def square(): # <- Function header
new_value = 4 ** 2 # <- Function body print(new_value)
square()
16
def square(value):
new_value = value ** 2
print(new_value)
square(4)
16
square(5)
25
def square(value): new_value = value ** 2 return new_value
num = square(4) print(num)
16
Docstrings describe what your function does
Serve as documentation for your function
Placed in the immediate line after the function header
In between triple double quotes """
def square(value):
"""Returns the square of a value."""
new_value = value ** 2
return new_value
Introduction to Functions in Python