PYW.png 2b: Functions in Python

Table of Contents

🎉Table of contents with working links🎉

1. Homework check?

1.1. Wolf, goat, cabbage

True = right False = left

wolf = True
cabbage = True
goat = True
farmer = True

var = 0

while wolf or cabbage or goat or farmer:

    if var == "wolf":
        if wolf == farmer:
            wolf = not wolf
            farmer = not farmer
        else:
            print("they are not on the same side, silly")
    elif var == "goat":
        if goat == farmer:
            goat = not goat
            farmer = not farmer
        else:
            print("they are not on the same side, silly")
    elif var == "cabbage":
        if cabbage == farmer:
            cabbage = not cabbage
            farmer = not farmer
        else:
            print("they are not on the same side, silly")
    elif var == "nothing":
        farmer = not farmer

    if ((wolf == goat) and (wolf != farmer)) or ((goat == cabbage) and goat != farmer):
        print("You failed")
        break

    if (not goat) and (not cabbage) and (not farmer) and (wolf):
        print("congratulatons!")

    print("wolf = " + str(wolf), "cabbage = " + str(cabbage), "goat = " + str(goat), "farmer = " + str(farmer), sep='\n')

    var = input("What should the farmer row across the river: ")

2. Built-in functions

A function is a sequence of statements that will be executed once it is invoked/called.

Python has some built-in functions. For example:

  • Checking the data type of a variable:
    • type()
    • isinstance()
  • Turning variables into a specific data type:
    • int()
    • float()
    • str()
  • Many others:
    • abs()
    • pow
    • round()
    • len()
  • With sequences (which we will treat later):
    • max()
    • min()
var1 = type(True)
var1 = isinstance(True, bool)

var1 = float(5)

print(var1)

print(type(var1))

print(abs(-4))

# doing the same thing
print(2**3)
print(pow(2,3))

print(round(3.51))

#length of string
print(len("hi"))

list1 = [1, 2, 5, 9]

print(max(list1))
print(min(list1))

A function takes one or more arguments.

It is important to seperate the arguments with a comma.

var1 = pow(2,3)

print(var1)

Remember that one of you "discovered" this functionality of the functin "print" last Tuesday.

print("this", "class", "has", "many", "students", sep = "?")

Some functions only take arguments of a particular kind:

print(int("hello"))

In Spyder, you can use ctrl+i (with cursor on function) to get more information on the function.

3. External modules

Many commonly used functions are available in external modules.

A module is a file that contains a collection of functions.

They become accesible after importing the appropiate module with the following syntax:

import module

All functions in a module are available, but we need to prefix them with the name of the module (and a dot) to identiy their source.

import math

print(math.cos(10))

You can also import a few objects from the module:

from math import pi

print(pi)

(This does not work)

print(pi)

Important: by convention, import-statements are at the very top of a program.

4. Fruitful vs void functions

A function might or might not "return" a value.

A function that does not return a value, is called void.

A function that does yield results are sometimes called 'fruitful'.

Remember the difference between an expression and a statement.

A piece of code that runs a fruitful function is an expression: it produces a value.

A piece of code that runs a void function is a statement: it does not produce a value.

You can save the output of fruitful function in a variable. For a void function that would not make sense.

4.1. Fruitful

var1 = len("fruit flies like a banana")

print(var1)

4.2. Void

There are a lot of functions that simply "do stuff". They don't ouput a value.

If you nonetheless save the (non-existing) output value of a void function to a variable, the output has the data type "NoneType".

var1 = print("time flies like arrow, fruitflies like a banana")

print(var1)
print(type(var1))

The script below opens an url in your default web broswer. Should work on your computers as well.

import webbrowser

var1 = webbrowser.open('www.nos.nl')

print(var1)

Script below sends an email. (This requires a bit of extra set-up, and probably does not work on your computer).

import subprocess

email_content = """From: work@mishavelthuis.nl
Subject: Another example

Dear Clio,

This is yet another example.

Thanks for being the guinnea pig.

Groetjes,

Misha
"""

recipient = "clio.votsis@student.uva.nl"

process = subprocess.Popen(['msmtp', '--from=work@mishavelthuis.nl', recipient], stdin=subprocess.PIPE)

var1 = process.communicate(email_content.encode('utf-8'))

print(var1)
print(type(var1))

5. Self-defined functions

The basic format for creating your own function in Python is:

def <function_name>(<parameters>):
    <statement>
    ...
    <statement>

In the definition of a function, the input variables are called parameters. When executing the function, the variables that you feed to the function are called arguments.

You can say that the parameters (within the function) receive their values when the function is called with an actual argument.

The collections of statements is called block. In Python, a block is marked by indentation, and announced by a colon (:).

def doge_function(s):
        return len(s)

def doge_function(s):
    if "DEI" in s:
        print("delete document")

var1 = doge_function("The FAPdei is the main document in the AUC that describes how, as a community we deal with issues of diversity, inclusivity and equity")        

print(var1)
print(type(var1))

Is this a void or a fruitful function?

A fruitful function returns a value. To do this you use the keyword <return>:

from math import pi

def surface_circle(r):
    surface = 2 * pi * r**2
    return surface

var1 = surface_circle(3)
print(var1)

Important: the position of the arguments determines to which parameter they are assigned.

from math import pi

def surface_cilinder(r,h):
    top = 2 * pi * r**2
    bottom = 2 * pi * r**2
    side = 2 * pi * r**2 * h
    return top+bottom+side

radius = 3
height = 2

var1 = surface_cilinder(height, radius)

print(var1)

6. Global and local variables

Most programming languages distinguish local from global variables.

Global variables: are available to the entire program.

Local variables: are only visible inside the block where they are declared.

The program part in which a variable can be used, is called the scope of that variable.

By assigning a value to a variable in the block (‘body’) of a function definition, a local copy of that variable is created in the function. This copy is only available within that function.

from math import pi

def surface_cilinder(r,h):
    top = 2 * pi * r**2
    bottom = 2 * pi * r**2 #<- declared within the function. Local variable. Only available within the function
    side = 2 * pi * r**2 * h
    radius = "blablabla"
    print("Inside the function: bottom =",bottom)
    print("Inside the function: radius =",radius)
    return top+bottom+side

radius = 3 #<- declared outside the function in the main program. Global variable. Available everywhere.
height = 2

var1 = surface_cilinder(radius, height)

print("Outside the function: radius =", radius)
print("Outside the function: bottom =", bottom)

7. Why functions

There are several reasons to build a program composed of several functions that work together.

  • Breaking the program into functions make the program easier to read and debug
  • Help to eliminate/reduce repetitive code
  • It is easier to debug independent functions, one by one, and then assemble them all toegther.
  • Functions can be reused in the same code or in other programs.

Created: 2025-02-28 vr 09:24