Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function
definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Arbitrary Arguments are often shortened to *args in Python documentations.
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.
Arbitrary Keyword Arguments,
**kwargs
If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and can access
the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Arbitrary Kword Arguments are often shortened to **kwargs in Python
documentations.
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement
function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.
Example
def myfunction():
pass
Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or ONLY
keyword arguments.
To specify that a function can have only positional arguments, add , / after
the arguments:
Example
def my_function(x, /):
print(x)
my_function(3)
Without the , / you are actually allowed to use keyword arguments even if
the function expects positional arguments:
Example
def my_function(x):
print(x)
my_function(x = 3)
But when adding the , / you will get an error if you try to send a keyword
argument:
Example
def my_function(x, /):
print(x)
my_function(x = 3)
Keyword-Only Arguments
To specify that a function can have only keyword arguments,
add *, before the arguments:
Example
def my_function(*, x):
print(x)
my_function(x = 3)
Without the *, you are allowed to use positionale arguments even if the
function expects keyword arguments:
Example
def my_function(x):
print(x)
my_function(3)
But when adding the *, / you will get an error if you try to send a positional
argument:
Example
def my_function(*, x):
print(x)
my_function(3)
Combine Positional-Only and
Keyword-Only
You can combine the two argument types in the same function.
Any argument before the / , are positional-only, and any
argument after the *, are keyword-only.
Example
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
Recursion
Python also accepts function recursion, which means a defined function can
call itself.
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
In this example, tri_recursion() is a function that we have defined to call
itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Lambda functions can take any number of arguments:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the
number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that
always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same
program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Python Arrays
Note: Python does not have built-in support for Arrays, but Python Lists can
be used instead.
Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work
with arrays in Python you will have to import a library, like the NumPy library.
Arrays are used to store multiple values in one single variable:
Example
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Access the Elements of an Array
You refer to an array element by referring to the index number.
Example
Get the value of the first array item:
x = cars[0]
Example
Modify the value of the first array item:
cars[0] = "Toyota"
The Length of an Array
Use the len() method to return the length of an array (the number of
elements in an array).
Example
Return the number of elements in the cars array:
x = len(cars)
Note: The length of an array is always one more than the highest array
index.
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)
Adding Array Elements
You can use the append() method to add an element to an array.
Example
Add one more element to the cars array:
[Link]("Honda")
Removing Array Elements
You can use the pop() method to remove an element from the array.
Example
Delete the second element of the cars array:
[Link](1)
You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
[Link]("Volvo")
Note: The list's remove() method only removes the first occurrence of the
specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the curren
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Note: Python does not have built-in support for Arrays, but Python Lists can
be used instead.
Python Classes and Objects
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
The __init__() Function
The examples above are classes and objects in their simplest form, and are
not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in
__init__() function.
All classes have a function called __init__(), which is always executed when
the class is being initiated.
Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for
name and age:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print([Link])
print([Link])
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
The __str__() Function
The __str__() function controls what should be returned when the class object
is represented as a string.
If the __str__() function is not set, the string representation of the object is
returned:
Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print(p1)
Example
The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def __str__(self):
return f"{[Link]}({[Link]})"
p1 = Person("John", 36)
print(p1)
Object Methods
Objects can also contain methods. Methods in objects are functions that
belong to the object.
Let us create a method in the Person class:
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.
The self Parameter
The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it
has to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
[Link] = name
[Link] = age
def myfunc(abc):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
Modify Object Properties
You can modify properties on objects like this:
Example
Set the age of p1 to 40:
[Link] = 40
Delete Object Properties
You can delete properties on objects by using the del keyword:
Example
Delete the age property from the p1 object:
del [Link]
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
The pass Statement
class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to avoid getting
an error.
Example
class Person:
pass
Python Inheritance
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any
other class:
Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
#Use the Person class to create an object, and then execute the
printname method:
x = Person("John", "Doe")
[Link]()
Create a Child Class
To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods
from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other
properties or methods to the class.
Now the Student class has the same properties and methods as the Person
class.
Example
Use the Student class to create an object, and then execute
the printname method:
x = Student("Mike", "Olsen")
[Link]()
Add the __init__() Function
So far we have created a child class that inherits the properties and methods
from its parent.
We want to add the __init__() function to the child class (instead of
the pass keyword).
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit
the parent's __init__() function.
Note: The child's __init__() function overrides the inheritance of the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in
the __init__() function.
Use the super() Function
Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, you do not have to use the name of the parent
element, it will automatically inherit the methods and properties from its
parent.
Add Properties
Example
Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019
In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another
parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year
x = Student("Mike", "Olsen", 2019)
Add Methods
Example
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year
def welcome(self):
print("Welcome", [Link], [Link], "to the class
of", [Link])
Python Iterators
Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator
protocol, which consist of the methods __iter__() and __next__().
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
Example
Return an iterator from a tuple, and print each value:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:
Example
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Looping Through an Iterator
We can also use a for loop to iterate through an iterable object:
Example
Iterate the values of a tuple:
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
Example
Iterate the characters of a string:
mystr = "banana"
for x in mystr:
print(x)
The for loop actually creates an iterator object and executes the next()
method for each loop.
Create an Iterator
To create an object/class as an iterator you have to implement the
methods __iter__() and __next__() to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you to do some initializing when the
object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.),
but must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the
next item in the sequence.
Example
Create an iterator that returns numbers, starting with 1, and each sequence
will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration
The example above would continue forever if you had enough next()
statements, or if it was used in a for loop.
To prevent the iteration from going on forever, we can use
the StopIteration statement.
In the __next__() method, we can add a terminating condition to raise an
error if the iteration is done a specified number of times:
Example
Stop after 20 iterations:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
Python Polymorphism
The word "polymorphism" means "many forms", and in programming it
refers to methods/functions/operators with the same name that can be
executed on many objects or classes.
Function Polymorphism
An example of a Python function that can be used on different objects is
the len() function.
String
For strings len() returns the number of characters:
Example
x = "Hello World!"
print(len(x))
Tuple
For tuples len() returns the number of items in the tuple:
Example
mytuple = ("apple", "banana", "cherry")
print(len(mytuple))
Dictionary
For dictionaries len() returns the number of key/value pairs in the dictionary:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Class Polymorphism
Polymorphism is often used in Class methods, where we can have multiple
classes with the same method name.
For example, say we have three classes: Car, Boat, and Plane, and they all
have a method called move():
Example
Different classes with the same method:
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
[Link]()
Look at the for loop at the end. Because of polymorphism we can execute the
same method for all three classes.
Inheritance Class Polymorphism
What about classes with child classes with the same name? Can we use
polymorphism there?
Yes. If we use the example above and make a parent class called Vehicle,
and make Car, Boat, Plane child classes of Vehicle, the child classes inherits
the Vehicle methods, but can override them:
Example
Create a class called Vehicle and make Car, Boat, Plane child classes
of Vehicle:
class Vehicle:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car object
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object
for x in (car1, boat1, plane1):
print([Link])
print([Link])
[Link]()
Child classes inherits the properties and methods from the parent class.
In the example above you can see that the Car class is empty, but it
inherits brand, model, and move() from Vehicle.
The Boat and Plane classes also inherit brand, model, and move() from Vehicle,
but they both override the move() method.
Because of polymorphism we can execute the same method for all classes.
Python Scope
A variable is only available from inside the region it is created. This is
called scope.
Local Scope
A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.
Example
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Function Inside Function
As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable
and belongs to the global scope.
Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global
scope (outside the function) and one available in the local scope (inside the
function):
Example
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword.
The global keyword makes the variable global.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Also, use the global keyword if you want to make a change to a global
variable inside a function.
Example
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Nonlocal Keyword
The nonlocal keyword is used to work with variables inside nested functions.
The nonlocal keyword makes the variable belong to the outer function.
Example
If you use the nonlocal keyword, the variable will belong to the outer
function:
def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1())