Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed.

  1. The way to run a python file is like this on the command line:

    1
    C:\Users\*Your Name*>python helloworld.py
  2. Python can be run as a command line itself.

    Type the following on the Windows, Mac or Linux command line:

    1
    C:\Users\Your Name>python

    Or, if the “python” command did not work, you can try “py”:

    1
    C:\Users\Your Name>py

Indentation

Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

1
2
if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, but it has to be at least one.

You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:

Syntax Error:

1
2
3
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Variables

  • In Python, variables are created when you assign a value to it:

    1
    2
    3
    4
    x=5
    y="Hello"
    print(x)
    print(y)

    output

    1
    2
    5
    Hello
  • Variables do not need to be declared with any particular type, and can even change type after they have been set.

    1
    2
    3
    x=5
    x="Hello"
    print(x)

    output

    1
    Hello
  • String variables can be declared either by using single or double quotes:

    1
    2
    3
    x = "John"
    # is the same as
    x = 'John'
  • Casting

    If you want to specify the data type of a variable, this can be done with casting.

    1
    2
    3
    x = str(3)    # x will be '3'
    y = int(3) # y will be 3
    z = float(3) # z will be 3.0
  • Get the Type

    You can get the data type of a variable with the type() function.

    1
    2
    3
    4
    x = 5
    y = "John"
    print(type(x))
    print(type(y))
  • Variable name

    • A variable name must start with a letter or the underscore character
    • A variable name cannot start with a number
    • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    • Variable names are case-sensitive (age, Age and AGE are three different variables)
    • A variable name cannot be any of the Python keywords.
  • Output Variable

    In the print() function, you output multiple variables, separated by a comma:

    1
    2
    3
    4
    5
    6
    x="Python"
    y="is"
    z="awesome"
    print(x,y,z)

    #Python is awesome

    You can also use the + operator to output multiple variables:

    (But + will not separate the word by space. In the string , the function of + is concatenating the strings)

    1
    2
    3
    4
    x = "Python"
    y = "is"
    z = "awesome"
    print(x + ' ' + y + ' ' + z)

    For numbers, the + character works as a mathematical operator:

    1
    2
    3
    x = 5
    y = 10
    print(x + y)

    In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error:

    1
    2
    3
    x = 5
    y = "John"
    print(x + y)

    The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types:

    1
    2
    3
    x = 5
    y = "John"
    print(x, y)
  • Global Variables

    Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

    If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    x = "awesome"

    def myfunc():
    x = "fantastic"
    print("Python is " + x)

    myfunc()

    print("Python is " + x)
  • Global Keyword

    To create a global variable inside a function, you can use the global keyword.

    1
    2
    3
    4
    5
    6
    def myfunc():
    global x
    x = "fantastic"

    myfunc()
    print("Python is " + x)

Data Types

Python has the following data types built-in by default, in these categories:

Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

Setting the data type

Example Data Type
x = “Hello World” str
x = 20 int
x = 20.5 float
x = 1j complex
x = [“apple”, “banana”, “cherry”] list
x = (“apple”, “banana”, “cherry”) tuple
x = range(6) range
x = {“name” : “John”, “age” : 36} dict
x = {“apple”, “banana”, “cherry”} set
x = frozenset({“apple”, “banana”, “cherry”}) frozenset
x = True bool
x = b”Hello” bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
  • Get the data types

    You can get the data type of any object by using the type() function:

    1
    2
    3
    x = 5
    print(type(x))
    # <class 'int'>

Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

‘hello’ is the same as “hello”.

Multiline Strings

You can assign a multiline string to a variable by using three quotes, Or three single quotes:

1
2
3
4
5
6
7
8
9
10
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

1
2
3
a = "Hello, World!"
for i in a:
print(i)

String Length

To get the length of a string, use the len() function.

1
2
a = "Hello, World!"
print(len(a))

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

1
2
txt = "The best things in life are free!"
print("free" in txt)

Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

1
2
b = "Hello, World!"
print(b[2:5])

By leaving out the start index, the range will start at the first character:

1
2
b = "Hello, World!"
print(b[:5])

By leaving out the end index, the range will go to the end:

1
2
b = "Hello, World!"
print(b[2:])

Modify Strings

Python has a set of built-in methods that you can use on strings.

The upper() method returns the string in upper case:

1
2
a = "Hello, World!"
print(a.upper())

The lower() method returns the string in lower case:

1
2
a = "Hello, World!"
print(a.lower())

The strip() method removes any whitespace from the beginning or the end:

1
2
3
a = " Hello, World! "
print(a.strip())
# returns "Hello, World!"

The replace() method replaces a string with another string:

1
2
a = "Hello, World!"
print(a.replace("H", "J"))

The split() method returns a list where the text between the specified separator becomes the list items.

1
2
3
a = "Hello, World!"
print(a.split(","))
# returns ['Hello', ' World!']

Python Collections

There are four collection data types in the Python programming language:

  • Listis a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered and changeable. No duplicate members.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable means that we cannot change the items after the set has been created.

Duplicates Not Allowed Sets cannot have two items with the same value.

Lists

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

List items are ordered, changeable, and allow duplicate values.

  • Lists are created using square brackets:

    1
    2
    a=[1,2,3,4,5]
    print(a)

    output

    1
    [1, 2, 3, 4, 5]
  • A list can contain different data types:

    1
    list1 = ["abc", 34, True, 40, "male"]

The list() Constructor

It is also possible to use the list() constructor when creating a new list.

1
2
3
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
# ['apple', 'banana', 'cherry']

List Length

To determine how many items a list has, use the len() function:

1
2
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

output

1
3

Data Types

List items can be of any data type. A list can contain different data types:

1
list1 = ["abc", 34, True, 40, "male"]

Access List Items

List items are indexed and you can access them by referring to the index number:

1
2
3
thislist = ["apple", "banana", "cherry"]
print(thislist[0])
print(thislist[2])

output

1
2
apple
cherry

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

1
2
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

output

1
['cherry', 'orange', 'kiwi']

Note: The search will start at index 2 (included) and end at index 5 (not included). Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

1
2
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

output

1
['apple', 'banana', 'cherry', 'orange']

By leaving out the end value, the range will go on to the end of the list:

1
2
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

output

1
['cherry', 'orange', 'kiwi', 'melon', 'mango']

Insert items

To insert a new list item, without replacing any of the existing values, we can use the insert() method.

1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.insert(2,"hello")
print(thislist)

output

1
['apple', 'banana', 'hello', 'cherry']

Append Items

To add an item to the end of the list, use the append() method:

1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

output

1
['apple', 'banana', 'cherry', 'orange']

Extend List

To append elements from another list to the current list, use the extend() method.

1
2
3
4
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

output

1
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

Remove

The remove() method removes the specified item.

1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

output

1
['apple', 'cherry']

The pop() method removes the specified index.

1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

output

1
['apple', 'cherry']

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Loop Through a List

You can loop through the list items by using a for loop:

1
2
3
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Loop Through the Index Numbers

You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

range(5) function: Create a sequence of numbers from 0 to 4

1
2
3
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])

Using a While Loop

You can loop through the list items by using a while loop.

Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

Remember to increase the index by 1 after each iteration.

1
2
3
4
5
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1

Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

1
2
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

List Methods

Python has a set of built-in methods that you can use on lists.

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 current list
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 item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Tuples

Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets

1
2
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

1
2
3
4
5
6
7
8
9
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

#<class 'tuple'>
#<class 'str'>

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

1
2
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

1
2
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new tuple with the specified items.

1
2
3
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
#('cherry', 'orange', 'kiwi')

Add Items

Since tuples are immutable, they do not have a build-in append() method, but there are other ways to add items to a tuple.

  1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.

    1
    2
    3
    4
    5
    6
    thistuple = ("apple", "banana", "cherry")
    y = list(thistuple)
    y.append("orange")
    thistuple = tuple(y)
    print(thistuple)
    #('apple', 'banana', 'cherry', 'orange')
  2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:

    1
    2
    3
    4
    5
    thistuple = ("apple", "banana", "cherry")
    y = ("orange",)
    thistuple += y

    print(thistuple)

Remove Items

Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:

1
2
3
4
5
6
Convert the tuple into a list, remove "apple", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Loop Through a Tuple

Iterate through the items and print the values:

1
2
3
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

You can also loop through the tuple items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

1
2
3
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])

Using a While Loop

You can loop through the tuple items by using a while loop.

Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by referring to their indexes.

Remember to increase the index by 1 after each iteration.

1
2
3
4
5
thistuple = ("apple", "banana", "cherry")
i = 0 #define a variable i stared at 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1

Set

Sets are written with curly brackets.

A set is a collection which is unordered, unchangeable, unindexed, and Duplicates Not Allowed. So you cannot be sure in which order the items will appear.

1
2
3
thisset = {"apple", "banana", "cherry"}
print(thisset)
# {'banana', 'apple', 'cherry'}

Access Items

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

1
2
3
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

Check if “banana” is present in the set:

1
2
3
thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Add Items

Add an item to a set, using the add() method:

1
2
3
4
5
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add Sets

To add items from another set into the current set, use the update() method.

1
2
3
4
5
6
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).

1
2
3
4
5
6
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

1
2
3
4
5
thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Dictionaries

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered, changeable and do not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

1
2
3
4
5
6
7
thisdict={
"brand":"Ford",
"model":"Mustang",
"year":1964
}
print(thisdict["brand"])
# Ford

The dict() Constructor

1
2
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

1
2
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict["name"])

Get Keys

The keys() method will return a list of all the keys in the dictionary.

1
2
3
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict.keys())
# dict_keys(['name', 'age', 'country'])

Get Values

The values() method will return a list of all the values in the dictionary.

1
2
3
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict.values())
# dict_values(['John', 36, 'Norway'])

Get Items

The items() method will return each item in a dictionary, as tuples in a list.

1
2
3
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict.items())
# dict_items([('name', 'John'), ('age', 36), ('country', 'Norway')])

Change Values

You can change the value of a specific item by referring to its key name:

1
2
3
4
5
6
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary

The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

1
2
3
4
5
6
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

1
2
3
4
5
6
7
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.

1
2
3
4
5
6
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.

Removing Items

There are several methods to remove items from a dictionary:

The pop() method removes the item with the specified key name:

1
2
3
4
5
6
7
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

The clear() method empties the dictionary:

1
2
3
4
5
6
7
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Loop Through a Dictionary

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

1
2
3
4
5
6
thisdict = dict(name = "John", age = 36, country = "Norway")
for x in thisdict:
print(x)
# name
# age
# country

You can use the keys() method to return the keys of a dictionary:

1
2
for x in thisdict.keys():
print(x)

Return the values

1
2
3
4
5
6
7
thisdict = dict(name = "John", age = 36, country = "Norway")
for x in thisdict:
print(thisdict[x])

# John
# 36
# Norway

You can also use the values() method to return values of a dictionary:

1
2
for x in thisdict.values():
print(x)

Loop through both keys and values, by using the items() method:

1
2
3
4
5
6
7
thisdict = dict(name = "John", age = 36, country = "Norway")
for x,y in thisdict.items():
print(x,y)

name John
age 36
country Norway

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

If … Else

Conditions and If statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in “if statements” and loops.

If statements

1
2
3
4
a = 33
b = 200
if b > a:
print("b is greater than a")

Elif

The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.

1
2
3
4
5
6
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else

The else keyword catches anything which isn’t caught by the preceding conditions.

1
2
3
4
5
6
7
8
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

And

The and keyword is a logical operator, and is used to combine conditional statements:

1
2
3
4
5
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional statements:

1
2
3
4
5
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional statement:

1
2
3
4
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

1
2
3
4
5
a = 33
b = 200

if b > a:
pass

Loops

Python has two primitive loop commands:

  • while loops
  • for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

1
2
3
4
i=0
while i<6:
print(i)
i+=1

Note: remember to increment i, or else the loop will continue forever.

With the break statement we can stop the loop even if the while condition is true:

1
2
3
4
5
6
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

With the continue statement we can stop the current iteration, and continue with the next:

1
2
3
4
5
6
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

1
2
3
4
5
6
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

for x in "banana":
print(x)

The range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

1
2
3
for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

1
2
3
4
5
6
for x in range(2,6):
print(x)
2
3
4
5

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):

1
2
3
4
5
for x in range(2,6,2):
print(x)

2
4

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:

1
2
def my_function():
print("Hello from a function")

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.


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:

1
2
3
4
5
6
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

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:

1
2
3
4
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

1
2
3
4
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

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.

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Recursion

The process of repeating a function, each time applying it to the result of the previous stage.

Python also accepts function recursion, which means a defined function can call itself.

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.

As a example which is a function that counts the factorial:

1
2
3
4
5
6
7
8
9
10
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)

output

1
2
3
4
5
6
7
Recursion Example Results
1
3
6
10
15
21

As you can see, every time the statement result = k + tri_recursion(k - 1) is based on the previous result.

Lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

lambda *arguments* : *expression*

1
2
3
x = lambda a : a + 10
print(x(5))
# We pass the value 5 to a lambda function, which then executes the expression 5+10.
1
2
x = lambda a,b :a*b 
print(x(4,6))

Arrays

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

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

Create a class named MyClass, with a property named x:

1
2
class MyClass:
x = 5

Create an Object

1
2
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. Note: The __init__() function is called automatically every time the class is being used to create a new object.

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

1
2
3
4
5
6
7
8
class Person:
def __init__(self, name, age):
self.name=name
self.age=age

p1=Person("ferry", 20)
print(p1.name)
print(p1.age)

output

1
2
ferry
20

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.

1
2
3
4
5
6
7
8
9
class Person:
def __init__(self, name, age):
self.name=name
self.age=age
def greeting(self):
print("Hello, my name is "+ self.name)

p1=Person("ferry", 20)
p1.greeting()

output

1
Hello, my name is ferry

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:

1
2
3
4
5
6
7
8
9
10
11
12
Use the words *mysillyobject* and *abc* instead of *self*:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

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 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:

1
2
3
4
5
6
7
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

super() Function

super() function that will make the child class inherit all the methods and properties from its parent:

1
2
3
4
5
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)


Iterator vs Iterable

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

If you have learned C language, you can take an iterator in Python as an point in C

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:

1
2
3
4
5
6
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

output

1
2
3
apple
banana
cherry

Try & Except

  • The try block lets you test a block of code for errors.

  • The except block lets you handle the error.

  • The finally block lets you execute code, regardless of the result of the try- and except blocks.

As an example,

1
2
3
4
try:
print(x)
except:
print("An exception occurred")

The try block generate the except, because the x variable is not defined.

Since the try block raises an error, the except block will be executed.

output

1
An exception occurred

If there have not a try block, the program will crash and raise a error.

1
print(x)

output

1
2
3
4
Traceback (most recent call last):
File "try_except.py", line 1, in <module>
print(x)
NameError: name 'x' is not defined

Many Exceptions

You can define as many exceptions as you want.

And also you can execute a special except block for a special kind of error.

1
2
3
4
5
6
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

output

1
Variable x is not defined

Scope

A variable is only available from inside the region it is created. This is called scope.

Modules

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

The module can contain functions, but also variables of all types (arrays, dictionaries, objects etc)

Create a Module

To create a module just save the code you want in a file with the file extension .py

1
2
3
4
5
6
7
8
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

def greeting(name):
print("Hello, " + name)

Save this code in a file named mymodule.py

Use a Module

Now we can use the module we just created, by using the import statement:

1
2
3
4
import mymodule

mymodule.greeting("Jonathan")
print(myModule.person1)

Note: When using a function from a module, use the syntax: module_name.variable_name.

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Create an alias for mymodule called mx:

1
2
3
4
import mymodule as mx

a = mx.person1["age"]
print(a)

dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

List all the defined names belonging to the platform module:

1
2
3
4
import platform

x = dir(platform)
print(x)

Import From Module

You can choose to import only parts from a module, by using the from keyword.

1
2
3
from mymodule import person1

print (person1["age"])

File Handling

Python has several functions for creating, reading, updating, and deleting files.

open()

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

​ Using "w" you won’t be able to read the file.

"x" - Create - Creates the specified file, returns an error if the file exists

read()

The open() function returns a file object, which has a read() method for reading the content of the file:

1
2
f = open("demofile.txt", "r")
print(f.read())

write()

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

1
2
3
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

Note: the “w” method will overwrite the entire file.

1
2
3
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

close()

It is a good practice to always close the file when you are done with it.

1
2
3
f = open("demofile.txt", "r")
print(f.readline())
f.close()

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

1
2
import os
os.remove("demofile.txt")

with open

When you use with statement with open function, you do not need to close the file at the end, because with would automatically close it for you.

1
2
3
4
5
6
with open("text.txt", "w") as f:
f.write("welcome")

with open("text.txt","r") as f:
data=f.read()
print(data)

JSON in Python

Python has a built-in package called json, which can be used to work with JSON data.

If you have a JSON string, you can parse it by using the json.loads() method.

1
2
3
4
5
6
7
8
9
10
import json

# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import json

# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}

# convert into JSON:
y = json.dumps(x)

# the result is a JSON string:
print(y)

if __name__ == "__main__"

Python files are called modules and they are identified by the .py file extension. A module can define functions, classes, and variables.

__name__ is a model name. When a model is executed, __name__ equal to __main__. When a model is not executed, __name__ equal to its file name.

It’s boilerplate code that protects users from accidentally invoking the script when they didn’t intend to.

It allows the code in the module to be importable by other modules, without executing the code block beneath on import.