functions

About functions
Functions are a great way of organising your code. You can create a function and run it as many times as you want anywhere in your code. Variables you create in a function are called local variables and only work in that function. Variables that are in your main body of code, called global variables, won't work in a function, although there are ways round this. You can feed lots of things into a function. You put these into the brackets (parenthesis) and you can get one thing out by returning it. Functions are key to good coding but are best used once you understand lots of basics.

Where to put functions
Functions should be defined at the top of your code

Simple functions
These functions don't have any things fed into them and return nothing.
They just run whatever is inside them when they are used.
This function defines a simple pause, waiting for the user to type a key before the program moves on.
def pause():
    input("Press return to continue")

print("The monster creeps towards you")
pause()

#def creates the function
#Contents of the function pause()
#Further on in the code

#Runs pause() function
This would run as
>>>
The monster creeps towards you
Press return to continue
>>>
This simple function just prints a simple character animal
def petsmile():
    print("""
    _.-.
  '( ^{_}    (
    `~\`-----'\\
       )_)---)_)   
     Joan Stark
    """)

petsmile()
#Sets up a function called petsmile
#Prints everything between the triple speechmarks


#Needs a double \\ as a single one is used to tell the program not to print the next character




#Runs petsmile function

This would run as
>>>
    _.-.
  '( ^{_}    (
    `~\`-----'\
       )_)---)_)   
     Joan Stark
>>>
You can find more keyboard character (ascii) art here

Advanced Functions
Functions with inputs in the brackets but no useable return
Traffic Light program
Why not copy and adapt this example
Information is passed into the function and used in the repeat loop
Nothing useful is returned

import time
from time import sleep
from tkinter import *
tk=Tk()
win=Canvas(tk, width=55, height=200)
win.pack()
#Functions
def red(a):
    for i in range(a):
        red=win.create_oval(5,5,50,50, fill="red")
        tk.update()
        time.sleep(0.05)
def redb(a):
    for i in range(a):
        red=win.create_oval(5,5,50,50, fill="black")
        tk.update()
        time.sleep(0.05)
def amber(a):
    for i in range(a):
        amber=win.create_oval(5,55,50,100, fill="orange")
        tk.update()
        time.sleep(0.05)
def amberb(a):
    for i in range(a):
        amber=win.create_oval(5,55,50,100, fill="black")
        tk.update()
        time.sleep(0.05)
def green(a):
    for i in range(a):
        green=win.create_oval(5,105,50,150, fill="green")
        tk.update()
        time.sleep(0.05)
def greenb(a):
    for i in range(a):
        green=win.create_oval(5,105,50,150, fill="black")
        tk.update()
        time.sleep(0.05)
def lights():
    red=win.create_oval(5,5,50,50, fill="black")
    amber=win.create_oval(5,55,50,100, fill ="black")
    green=win.create_oval(5,105,50,150, fill="black")

#run functions
lights()
red(30)
redb(1)
amber(10)
amberb(1)
green(30)
greenb(1)


tk.mainloop()


Function with inputs in the brackets and a return

This function called multi multiplies two numbers and returns the answer
def multi(a,b):
    answer = a * b
    return answer

q1 = multi(5,100)
print(q1)

#a and b are spaces that must be filled by two bits of data.
#Times a and b and putting it into local variable answer
#Returning variable answer to main program

#Create variable q1 and put function multi with 5 replacing a and 100 replacing b into q1. Finally print q1
This would run as
>>>
500
>>>
NOTE The function returns the answer into itself which is why we need to put the function into a variable to use it.
This diagram may help to explain it more

This program uses the same function but gets the user to input the numbers.
def multi(a,b):
    answer = a * b
    return answer

num1 = int(input("Enter a whole number"))
num2 = int(input("Enter a second whole number"))
q1 = multi(num1,num2)
print(q1)

#Creates function called multi



#User puts a number into variable num1
#User puts a number into variable num2
#num1 and num2 are fed into multi in place of a and b and the answer is returned into q1. Finally q1 is printed


Global and local variables within a function

In this example although both variables are called fun one is inside the function and is a local variable and the other is outside the function and is a global variable. They are completely independent of each other.
fun = 6

def multi():
    fun = 6
    fun = fun * 3
    print("I am a local variable called fun inside multi=",fun)

multi()
print("I am a global variable called fun outside multi=",fun)

#Global variable


#Local variable

#Print local variable


#Print global variable

This would output as
>>>
I am a local variable called fun inside multi= 18
I am a global variable called fun outside multi= 6
>>>
NOTE The global variable remains 6 despite the local variable being multiplied by 3

Using a global variable inside a function

This comes with a warning. Far better computer scientists than me say that changing global variables inside a function is not a good idea.
fun = 6

def multi():
    global fun
    fun = fun * 3
    print(fun)

multi()
print(fun)

#Global variable fun setup with 6 inside it

#Function called multi setup
#Function is told that it is using global variable called fun
#Fun is multiplied by 3
#Fun is printed within function

#Function is run
#Fun is printed outside the function
This would output as
>>>
18
18
>>>
The global variable has been changed within the function
 
Comments