Back to: Python Programming
Functions are re-useable blocks of code. To invoke a function, you “call” it by placing a set of parenthesis “()” after the function name. A simple example of a function might be a message to contact tech support.
# function - A block of reuseable code
# place () after function name to invoke it
def contactTechSupport():
print("----------------------------------------")
print("If you have any problems, please contact")
print("Technical Support on 03 9876 1234")
print("----------------------------------------")
print()
print("Welcome to the program!")
print()
# Main Program Starts
contactTechSupport()
Arguments
An argument is a way for you to provide more information to a function. The function can then use that information as it runs, like a variable. Said differently, when you create a function, you can pass in data in the form of an argument, also called a parameter.
Positional Arguments
You can send data to a function using positional arguments so the function can use this data to achieve some task and return a result. A positional argument means the arguments passed must be in the same order as the parameters defined by the function.
def contactSupport(department, phone): # <-- The 'arguments' are the variables in the brackets
print("----------------------------------------")
print("If you have any problems, please contact")
print(f"{department} on {phone}")
print("----------------------------------------")
print()
print("Welcome to the program!")
print()
contactSupport("Accounts", "03 9876 1234") # <- order matters - we are sending two arguments
Welcome to the program!
----------------------------------------
If you have any problems, please contact
Accounts on 03 9876 1234
----------------------------------------
After sending arguments to a function, there may be instances where you want a result returned. This is achieved using the return statement.
def add(x, y):
z = x + y
return z
def subtract(x, y):
z = x - y
return z
def multipy(x, y):
z = x * y
return z
def divide(x, y):
z = x / y
return z
print(add(1, 2)) # <-- add function becomes the returned value
print(subtract(1, 10))
print(multipy(2, 20))
print(divide(15, 3))
3
-9
40
5.0
Default Arguments
If a function requires arguments but the arguments have been omitted, then the function can be set up to use default arguments and IF arguments ARE sent, they will over-ride the defaults.
def contactSupport(department='support', phone='9876 1289'):
print("----------------------------------------")
print("If you have any problems, please contact")
print(f"{department} on {phone}")
print("----------------------------------------")
print()
print("Welcome to the program!")
print()
#contactSupport("Accounts", "03 9876 1234") # <- order matters
contactSupport()
Welcome to the program!
----------------------------------------
If you have any problems, please contact
support on 9876 1289
----------------------------------------
Some Examples
Write a function that requires arguments for price, discount and GST. Set default argument for discount to 0% and GST to 10%. Default arguments must always come AFTER required arguments The solution without default arguments:
def net_price(sale_price, discount, gst):
return sale_price * (1-discount/100) * (1+gst/100)
print(net_price(500,50, 10))
If we set the default discount to 0% and the GST to always be 10%, we need only send the sale_price:
def net_price(sale_price, discount=0, gst=10):
return sale_price * (1-discount/100) * (1+gst/100)
print(net_price(500))
The argument position is important. You could call the function as follows:
print(net_price(500))
print(net_price(500, 20))
print(net_price(500, 20, 15))
A Count Up Module
lets create a “count up” module.
import time
def count(start, end):
for x in range(start, end+1): # <-- 2nd arg is exclusive
print(x, end=' ')
time.sleep(1) # <-- time modules sleep method pauses 1s
print("DONE!")
count(0, 10)
0 1 2 3 4 5 6 7 8 9 10 DONE!
Since most counting starts at 0, we could set start=0
def count(start=0, end):
this will fail because “parameter without a default follows parameter with a default.
import time
def count(end, start=0): #<-- parameter without default first
for x in range(start, end+1): #<-- 2nd arg is exclusive
print(x, end=' ')
time.sleep(1) #<-- time modules sleep method pauses 1s
print("DONE!")
count (5) # <-- this will be the “end” parameter
Keyword Arguments
An optional feature when sending arguments to a function is that we can prefix an argument with the name of the parameter. Keyword arguments can help with code readability. These are keyword arguments. Note that the first argument has no keyword, this will be treated as a positional argument.
def hello(greeting, title, first, last):
print(f"{greeting} {title} {first} {last}")
hello("Hello", title="Mr.", last="Down", first="Bob")
Hello Mr. Bob Down
Order does not matter when using keyword arguments. Keyword arguments, however, must follow positional argument if mixing them.
def hello(greeting, title, first, last):
print(f"{greeting} {title} {first} {last}")
hello(title="Mr.", greeting="Hello", last="Down", first="Bob")
Hello Mr. Bob Down
Built in Arguments
The “print” function has some in-built arguments, including end and sep:
for number in range(1, 11):
print(number, end=" ") #<-- "end" is a keyword argument
# within print
print("1", "2", "3", "4", "5", sep="~")
# "sep" is another keyword argument within print
1~2~3~4~5
Exercise:
Create a function to generate a phone number. We need to pass in a country code, area code, first 4 digits then last 4 digits.
def get_phone(country, area, first, last):
return f"+{country} {area} {first} {last} "
phone_num = get_phone(country=61,area=3,first=9876,last=7890)
print(phone_num)
+61 3 9876 7890
Python Functions: Learn Via Quick Coding Project For Beginners – (10m:03s)