Python Notes Complete
Python Notes Complete
What is Python
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
print("Hello, World!")
Get Started With Python
1 Download Python
2 Install Python in Your System
Python Install
However, if you want to run Python on your own computer, follow the
instructions below.
Many Windows PCs and Mac computers already have Python pre-
installed.
python --version
If Python is not installed on your computer, you can download it for free
from the official website: ://[Link]/ https
Python QuickStart
[Link]:
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:
Hello, World!
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Example
if 5 > 2:
print("Five is greater than two!")
Comments
Python has commenting capability for the purpose of in-code
documentation.
Comments start with a #, and Python will render the rest of the line as a
comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Example
print("Hello"); print("How are you?");
print("Bye bye!")
Print Text
You have already learned that you can use the print() function to
display text or output values:
Example
print("Hello World!")
You can use the print() function as many times as you want. Each call
prints text on a new line by default:
Example
print("Hello World!")
print("I am learning Python.")
print("It is awesome!")
Double Quotes
Text in Python must be inside quotes. You can use either " double
quotes or ' single quotes:
Example
print("This will work!")
print('This will also work!')
Print Without a New Line
If you want to print multiple words on the same line, you can use
the end parameter:
Example
print("Hello World!", end=" ")
print("I will print on the same line.")
Note that we add a space after end=" " for better readability.
print(3)
print(358)
print(50000)
print(3 + 3)
print(2 * 5)
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the
rest of the line:
Example
print("Hello, World!") #This is a comment
Variables
Creating Variables
Python has no command for declaring a variable.
Example
x = 5
y = "John"
print(x)
print(y)
Casting
If you want to specify the data type of a variable, this can be done with
casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Example
x = "John"
# is the same as
x = 'John'
Case - Sensitive
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
Variables Name
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Output Variables
The print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them
the result would be "Pythonisawesome".
Example
x = 5
y = 10
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples
in the previous pages) are known as global variables.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Variables can store data of different types, and different types can do
different things.
Example
Print the data type of the variable x:
x = 5
print(type(x))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
• int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a
whole number)
• float() - constructs a float number from an integer literal, a float literal or a
string literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Multilne Strings
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Slicing
Specify the start index and the end index, separated by a colon, to return
a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[:5])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very
often you want to remove this space.
Example
The strip() method removes any whitespace from the beginning
or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("H", "J"))
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances
of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Booleans represent one of two values: True or False.
Boolean Values
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and Python
returns the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Pyhon Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetics Operators
Examples
Here is an example using different arithmetic operators:
Example
x = 15
y = 4
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x ** y)
print(x // y)
Division in Python
Python has two division operators:
Assignment Operators
Assignment operators are used to assign values to variables:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Comparison Operators
== Equal x == y
!= Not equal x != y
Examples
Comparison operators return True or False based on the comparison:
== Equal x == y
!= Not equal x != y
> Greater than x>y
Example
x = 5
y = 3
print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y)
Logical Operators
Logical operators are used to combine conditional statements:
Not Reverse the result, returns False if the result is not(x < 5
true and x < 10)
Identity Operators
Identity operators are used to compare the objects, not if they are equal,
but if they are actually the same object, with the same memory location:
is not Returns True if both variables are not the same x is not y
object
Example
The is operator returns True if both variables point to the same object:
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)
print(x is y)
print(x == y)
Example
The is not operator returns True if both variables do not point to the
same object:
x = ["apple", "banana"]
y = ["apple", "banana"]
print(x is not y)
• x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)
print(x is y)
Membership Operators
Membership operators are used to test if a sequence is presented in an
object:
not in Returns True if a sequence with the specified value is not x not in
present in the object y
Example
Check if "banana" is present in a list:
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
Example
Check if "pineapple" is NOT present in a list:
fruits = ["apple", "banana", "cherry"]
Membership in Strings
The membership operators also work with strings:
Example
text = "Hello World"
print("H" in text)
print("hello" in text)
print("z" not in text)
Bitwise Operators
<< Zero fill left Shift left by pushing zeros in from the right x << 2
shift and let the leftmost bits fall off
Example
The & operator compares each bit and set it to 1 if both are 1, otherwise
it is set to 0:
print(6 & 3)
The binary representation of 6 is 0110
The binary representation of 3 is 0011
Then the & operator compares the bits and returns 0010, which is 2 in
decimal.
List
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.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of
the list.
Note: There are some list methods that will change the order, but in
general: the order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items – Data Types
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
Type()
From Python's perspective, lists are defined as objects with the data
type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
List items are indexed and you can access them by referring to the index
number:
Note: The search will start at index 2 (included) and end at index 5 (not included).
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.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Example=
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Example
Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Note: The length of the list will change when the number of items inserted does not
match the number of items replaced.
Insert Items
To insert a new list item, without replacing any of the existing values, we
can use the insert() method.
Note: As a result of the example above, the list will now contain 4 items.
Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
Insert Items
To insert a list item at a specified index, use
the insert() [Link] insert() method inserts an item at the
specified index:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)
Note: As a result of the examples above, the lists will now contain 4 items.
If there are more than one item with the specified value,
the remove() method removes the first occurrence:
Example
Remove the first occurrence of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
[Link]("banana")
print(thislist)
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
Example
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)
Example
Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
[Link]()
print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True:
Example
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link](reverse = True)
print(thislist)
Copy a List
You can use the built-in List method copy() to copy a list.
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = [Link]()
print(mylist)
Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
Another way to join two lists is by appending all the items from list2 into
list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
[Link](x)
print(list1)
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
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
Tuple Items
Tuples are used to store multiple items in a single variable.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Ordered
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item
has index [1] etc.
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items
Since tuples are immutable, they do not have a built-
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.
Example
Convert the tuple into a list, add "orange", and convert it back into
a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Note: When creating a tuple with only one item, remember to include a
comma after the item, otherwise it will not be identified as a tuple.
Remove Items
Note: You cannot remove items in a tuple.
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:
Example
Convert the tuple into a list, remove "apple", and convert it back
into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)
Set
Sets are used to store multiple items in a single variable.
* Note: Set items are unchangeable, but you can remove items and add
new items.
Note: Sets are unordered, so you cannot be sure in which order the items will
appear.
Set Items
Unordered
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
Set items are unchangeable, meaning that we cannot change the items
after the set has been created.
Once a set is created, you cannot change its items, but you can remove
items and add new items.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Note: The values True and 1 are considered the same value in sets, and
are treated as duplicates:
Example
True and 1 is considered the same value:
thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)
Note: The values False and 0 are considered the same value in sets, and
are treated as duplicates:
Example
False and 0 is considered the same value:
thisset = {"apple", "banana", "cherry", False, True, 0}
print(thisset)
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.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
Add Items
Once a set is created, you cannot change its items, but you can add new
items.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use
the update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)
Remove Item
To remove an item in a set, use the remove(), or
the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an
error.
You can also use the pop() method to remove an item, but this method
will remove a random item, so you cannot be sure what item that gets
removed.
x = [Link]()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you do not know which
item that gets removed.
Loop Items
You can loop through the set items by using a for loop:
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Dictionary
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have
a defined order, and that order will not change.
Unordered means that the items do not have a defined order, you
cannot refer to an item by using an index.
Changeable
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name,
inside square brackets:
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Change Values
You can change the value of a specific item by referring to its key
name:
Example
Change the "year" to 2018:
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.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary
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.
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions
before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() method to return values of a
dictionary:
for x in [Link]():
print(x)
Example
You can use the keys() method to return the keys of a dictionary:
for x in [Link]():
print(x)
Example
Loop through both keys and values, by using the items() method:
for x, y in [Link]():
print(x, y)
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)
Another way to make a copy is to use the built-in function dict().
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
To access items from a nested dictionary, you use the name of the
dictionaries, starting with the outer dictionary:
Example
Print the name of child 2:
print(myfamily["child2"]["name"])
Dictionary Methods
Python has a set of built-in methods that you can use on
dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the
key, with the specified value
• 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
a = 33
b = 200
if b > a:
print("b is greater than a")
The elif keyword allows you to check multiple expressions for True and
execute a block of code as soon as one of the conditions evaluates
to True.
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Example
Testing multiple conditions:
score = 75
day = 4
match day:
case 6:
print("Today is Saturday")
case 7:
print("Today is Sunday")
case _:
print("Looking forward to the Weekend")
Loops
• while loops
• for loops
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while
condition is true:
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The range() Function
Example
Using the range() function:
for x in range(6):
print(x)
Example
Using the start parameter:
for x in range(2, 6):
print(x)
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the
"outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Functions
A function is a block of code which only runs when it is called.
Creating a Function
Example
def my_function():
print("Hello from a function")
my_function()
my_function()
my_function()
Function Names
Function names follow the same rules as variable names in Python:
Example
Valid function names:
calculate_sum()
_private_function()
myFunction2()
It's good practice to use descriptive names that explain what the function does.
Parameters vs Arguments
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Example
def my_function(name): # name is a parameter
print("Hello", name)
my_function("Emil")
my_function("Tobias")
my_function()
my_function("Linus")
Function Types
Global Scopes
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)
Python Range
This set of numbers has its own data type called range.
Creating ranges
The range() function can be called with 1, 2, or 3 arguments, using
this syntax:
range(start, stop, step)
Global Keyword
print(x)
Example
Create a range of numbers from 3 to 9:
x = range(3, 10)
The step value means the difference between each number in the
sequence. It is optional, and if not provided, it defaults to 1.
Using Range
Example
Iterate over each value in a range:
for i in range(10):
print(i)
Example
Convert different ranges to lists:
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(5, 20, 3)))
Slicing Ranges
Like other sequences, ranges can be sliced to extract a subsequence.
Example
Extract a subsequence from a range:
r = range(10)
print(r[2])
print(r[:3])
Length
Ranges support the len() function to get the number of elements in the
range.
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.
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?
An array can hold many values under a single name, and you can access
the values by referring to an index number.
Example
Get the value of the first array item:
x = cars[0]
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.
Python Modules
What is a Module ?
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
Save this code in a file named [Link]
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using
the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
[Link]("Jonathan")
Variables in Module
The module can contain functions, as already described, but also
variables of all types (arrays, dictionaries, objects etc):
Example
Save this code in the file [Link]
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for
other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
You can use the else keyword to define a block of code to be executed
if no errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try
block raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Python PIP
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
What is a Package?
Modules are Python code libraries you can include in your project.
Example
Check PIP version:
pip --version
Download a Package
Open the command line interface and tell PIP to download the package
you want.
Example
Download a package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>pip install camelcase
F-String was introduced in Python 3.6, and is now the preferred way of
formatting strings.
Example
Create an f-string:
Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)
Example
Display the price with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
txt = f"The price is {20 * 59} dollars"
print(txt)
Example
Add taxes before displaying the price:
price = 59
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)
Python None
Example
Assign and display a None value:
x = None
print(x)
Example
Assign and print the data type of a None value:
x = None
print(type(x))
User Input
Python allows for user input.
The following example asks for your name, and when you enter a name,
it gets printed on the screen:
Example
Ask for user input:
Python stops executing when it comes to the input() function, and continues when
the user has given some input.
Multiple Inputs
You can add as many inputs as you want, Python will stop executing at
each of them, waiting for user input:
Example
Multiple inputs:
Python Datetime
A date in Python is not a data type of its own, but we can import a
module named datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime
x = [Link]()
print(x)
Example
Return the year and name of weekday:
import datetime
x = [Link]()
print([Link])
print([Link]("%A"))
Directive Description Example
%Z Timezone CST
%C Century 20
%x Local version of date 12/31/18
%% A % character %
What is OOP?
OOP stands for Object-Oriented Programming.
Class 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)
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
Multiple Objects
You can create multiple objects from the same class:
Example
Create three objects from the MyClass class:
p1 = MyClass()
p2 = MyClass()
p3 = MyClass()
print(p1.x)
print(p2.x)
print(p3.x)
Example
Use self to access class properties:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
print("Hello, my name is " + [Link])
p1 = Person("Emil", 25)
[Link]()
Note: The self parameter must be the first parameter of any method in
the class.
Without self, Python would not know which object's properties you want
to access:
Example
The self parameter links the method to the specific object:
class Person:
def __init__(self, name):
[Link] = name
def printname(self):
print([Link])
p1 = Person("Tobias")
p2 = Person("Linus")
[Link]()
[Link]()
Example
Create a class named Person, use the __init__() method to assign values
for name and age:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("Emil", 36)
print([Link])
print([Link])
Note: The __init__() method is called automatically every time the class
is being used to create a new object.
Without the __init__() method, you would need to set properties
manually for each object:
Example
Create a class without __init__():
class Person:
pass
p1 = Person()
[Link] = "Tobias"
[Link] = 25
print([Link])
print([Link])
Example
With __init__(), you can set initial values when creating the object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("Linus", 28)
print([Link])
print([Link])
You can also set default values for parameters in the __init__() method:
Example
Set a default value for the age parameter:
class Person:
def __init__(self, name, age=18):
[Link] = name
[Link] = age
p1 = Person("Emil")
p2 = Person("Tobias", 25)
print([Link], [Link])
print([Link], [Link])
Multiple Parameters
The __init__() method can have as many parameters as you need:
Example
Create a Person class with multiple parameters:
class Person:
def __init__(self, name, age, city, country):
[Link] = name
[Link] = age
[Link] = city
[Link] = country
print([Link])
print([Link])
print([Link])
print([Link])
Class Properties
Properties are variables that belong to a class. They store data for each
object created from the class.
Example
Create a class with properties:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("Emil", 36)
print([Link])
print([Link])
Access Properties
You can access object properties using dot notation:
Example
Access the properties of an object:
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
print([Link])
print([Link])
Modify Properties
You can modify the value of properties on objects:
Example
Change the age property:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("Tobias", 25)
print([Link])
[Link] = 26
print([Link])
Example
Add a new property to an object:
class Person:
def __init__(self, name):
[Link] = name
p1 = Person("Tobias")
[Link] = 25
[Link] = "Oslo"
print([Link])
print([Link])
print([Link])
Class Methods
Methods are functions that belong to a class. They define the behavior of
objects created from the class.
Example
Create a method in a class:
class Person:
def __init__(self, name):
[Link] = name
def greet(self):
print("Hello, my name is " + [Link])
p1 = Person("Emil")
[Link]()
Example
Create a method with parameters:
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print([Link](5, 3))
print([Link](4, 7))
Example
A method that accesses object properties:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def get_info(self):
return f"{[Link]} is {[Link]} years old"
p1 = Person("Tobias", 28)
print(p1.get_info())
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.
Types of Inheritance:
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]()
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.
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
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
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!")
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!")
Python Encapsulation
Encapsulation is about protecting data inside a class.
This prevents accidental changes to your data and hides the internal
details of how your class works.
Private Properties
In Python, you can make properties private by using a double
underscore __ prefix:
Example
Create a private class property named __age:
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age # Private property
p1 = Person("Emil", 25)
print([Link])
print(p1.__age) # This will cause an error
Example
Use a getter method to access a private property:
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age
def get_age(self):
return self.__age
p1 = Person("Tobias", 25)
print(p1.get_age())
Example
Use a setter method to change a private property:
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age
def get_age(self):
return self.__age
p1 = Person("Tobias", 25)
print(p1.get_age())
p1.set_age(26)
print(p1.get_age())
Example
Use encapsulation to protect and validate data:
class Student:
def __init__(self, name):
[Link] = name
self.__grade = 0
def get_grade(self):
return self.__grade
def get_status(self):
if self.__grade >= 60:
return "Passed"
else:
return "Failed"
student = Student("Emil")
student.set_grade(85)
print(student.get_grade())
print(student.get_status())
Note: A single underscore _ is just a convention. It tells other programmers that the
property is intended for internal use, but Python doesn't enforce this restriction.
An inner class is a class defined inside another class. The inner class can
access the properties and methods of the outer class.
Inner classes are useful for grouping classes that are only used in one
place, making your code more organized.
Example
Create an inner class:
class Outer:
def __init__(self):
[Link] = "Outer Class"
class Inner:
def __init__(self):
[Link] = "Inner Class"
def display(self):
print("This is the inner class")
outer = Outer()
print([Link])
Example
Access the inner class and create an object:
class Outer:
def __init__(self):
[Link] = "Outer"
class Inner:
def __init__(self):
[Link] = "Inner"
def display(self):
print("Hello from inner class")
outer = Outer()
inner = [Link]()
[Link]()
Accessing Outer Class from Inner
Class
Inner classes in Python do not automatically have access to the outer
class instance.
If you want the inner class to access the outer class, you need to pass the
outer class instance as a parameter:
Example
Pass the outer class instance to the inner class:
class Outer:
def __init__(self):
[Link] = "Emil"
class Inner:
def __init__(self, outer):
[Link] = outer
def display(self):
print(f"Outer class name: {[Link]}")
outer = Outer()
inner = [Link](outer)
[Link]()
Example
Create multiple inner classes:
class Computer:
def __init__(self):
[Link] = [Link]()
[Link] = [Link]()
class CPU:
def process(self):
print("Processing data...")
class RAM:
def store(self):
print("Storing data...")
computer = Computer()
[Link]()
[Link]()
Abstraction hides the internal implementation details while exposing only the necessary
functionality. It helps focus on "what to do" rather than "how to do it."
Types of Abstraction:
• Partial Abstraction: Abstract class contains both abstract and concrete methods.
• Full Abstraction: Abstract class contains only abstract methods (like interfaces).
Example: In this example, we create an abstract Dog class with an abstract method
(sound) and a concrete method. Subclasses implement the abstract method while
inheriting the concrete method.
Explanation:
• Partial Abstraction: The Dog class has both abstract (sound) and concrete
(display_name) methods.
• Why Use It: Abstraction ensures consistency in derived classes by enforcing the
implementation of abstract methods.