
Overview
A Python function is a block of code that only runs when called. Data, known as parameters, can be passed to a function, and a result can be returned.
Creating a Function
A function is defined using the def keyword.
def my_function():
print("Hello from my function!")
Calling a Function
To call a function, use the function name followed by parenthesis.
def my_function():
print("Hello from my function!")
my_function()
Output:
Hello from my function!
Passing Arguments to a Function
Arguments (sometime referred to as parameters) are specified after the function name, inside the parentheses. Multiple arguments can be added separated by commas (model, year).
The following has a function with one argument (model). When the function is called, the argument is passed to the argument and used, in this case, to print the brand and model.
def my_function(model):
print("Maserati " + model)
my_function("Ghibli")
my_function("Quattroporte")
Output:
Maserati Ghibli
Maserati Quattroporte
Note
By default, a function must be called with the correct number of arguments. If your function expects 2 arguments, you have to call the function with 2 arguments.
Unknown Number of Arguments:
If you do not know how many arguments that will be passed into a function, an * can be added before the parameter name in the function definition.
This will signify to the function that it will receive a tuple of arguments.
def my_function(*cars):
print("The last car bought was a " + cars[2] + ".")
my_function("Maserati", "Alfa Romeo", "Maserati")
Output:
The last car bought was a Maserati.
Keyword Arguments:
Arguments can also be sent to the function using key = value syntax. This way the order of the arguments does not matter.
def my_function(car3, car2, car1):
print("The newest car is a " + car3 + ".")
my_function(car1 = "Maserati", car2 = "Alfa Romeo", car3 = "Maserati")
Output:
The newest car is a Maserati.
Unknown Number of Keyword Arguments:
If the number of keyword arguments is unknown, ** can be added before the parameter name in the function definition.
This will signify to the function that it will receive a dictionary of arguments.
def my_function(**car):
print("The car's model is a " + car["model"] + ".")
my_function(brand = "Maserati", model = "Quattroporte")
Output:
The car's model is a Quattroporte.
Setting a Default Parameter Value
If a function is called without providing an argument, the default value is used.
def my_function(name = "Johnny"):
print("My son's name is " + name + ".")
my_function("Marc")
my_function("Jack")
my_function()
my_function("Jimbo")
Output:
My son's name is Marc.
My son's name is Jack.
My son's name is Johnny.
My son's name is Jimbo.
Passing a List as an Argument
Any data type can be used as an argument to a function (string, number, list, dictionary etc.). it will be treated as, and remain, the same data type inside the function.
def my_function(cars):
for x in cars:
print(x)
cars = ["Ferrari", "Maserati", "Alfa Romeo"]
my_function(cars)
Output:
Ferrari
Maserati
Alfa Romeo
Returning a Value from an Argument
def my_function(x):
return x * x + 3
print(my_function(1))
print(my_function(3))
print(my_function(5))
Output:
4
12
28
Using the pass Statement
Python function definitions cannot be empty, but if there is a need to have a function definition with no content, the pass statement is used to avoid getting an error.
def myfunction():
pass
Output:
#there will be no output, and no error will be thrown
Positional-Only Arguments
A function can be specified to have ONLY positional arguments by adding ,/ after the arguments.
def my_function(x, /):
print(x)
my_function("Johnny")
Output:
Johnny
Keyword-Only Arguments
A function can be specified to have ONLY keyword arguments by adding *, after the arguments.
def my_function(*, x):
print(x)
my_function("Johnny")
Output:
Johnny
Combining Positional-Only and Keyword-Only Arguments
Any arguments before the / , are positional-only, and any arguments after the *, are keyword-only.
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(1, 2, c = 3, d = 4)
Output:
10
Function Recursion
In Python a defined function can call itself. This is called recursion.
This has the benefit in that data can be looped through to reach a result.
def my_recursion(k):
if(k > 0):
result = k + my_recursion(k - 1)
print(result)
else:
result = 0
return result
my_recursion(3)
Output:
1
3
6
Note
Beware: it is all too easy to write a function which never terminates, or one that uses excess amounts of memory or processor power.
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
- Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
- Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), unindexed (items cannot be referred to by index or key), and duplicates are NOT ALLOWED
- As of v3.7, Python dictionaries are ordered and duplicates ARE ALLOWED; in v3.6 and earlier, dictionaries were unordered (did not have a defined order and could not be referred to using an index)
- Python does not have built-in support for arrays, but Python lists can be used as pseudo “arrays”; therefore, all Python list methods will work with these pseudo “arrays”
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.