User-defined functions

Introduction to Functions in Python

Hugo Bowne-Anderson

Instructor

What you will learn:

  • Define functions without parameters

  • Define functions with one parameter

  • Define functions that return a value

  • Later: multiple arguments, multiple return values

Introduction to Functions in Python

Built-in functions

  • str()
x = str(5)

print(x)
'5'
print(type(x))
<class 'str'>
Introduction to Functions in Python

Defining a function

def square():    # <- Function header

new_value = 4 ** 2 # <- Function body print(new_value)
square()
16
Introduction to Functions in Python

Function parameters

def square(value):
    new_value = value ** 2
    print(new_value)

square(4)
16
square(5)
25
Introduction to Functions in Python

Return values from functions

  • Return a value from a function using return
def square(value):
    new_value = value ** 2
    return new_value

num = square(4) print(num)
16
Introduction to Functions in Python

Docstrings

  • 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

Let's practice!

Introduction to Functions in Python

Preparing Video For Download...