Python Tutorial
Python Tutorial
A. Rehman classes
Introduction
• What is Python?
• Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
• What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software development.
• Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.
• Good to know
• The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than
security updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or
Eclipse which are particularly useful when managing larger collections of Python files.
• Python Syntax compared to other programming languages
• Python was designed for readability, and has some similarities to the English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-
brackets for this purpose.
Simple Program
• print("Hello, World!")
Python Install
• if 5 > 2:
print("Five is greater than two!")
• Python will give you an error if you skip the indentation:
• if 5 > 2:
print("Five is greater than two!")
• he number of spaces is up to you as a programmer, but it
has to be at least one
• if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Python Comments
• This is a comment
written in
more than just one line
"""
print("Hello, World!")”””
• ‘’’
print("Hello, World!")’’’
Python Variables
• Creating Variables
• Python has no command for declaring a
variable.
• A variable is created the moment you first
assign a value to it.
• x=5
y = "John"
print(x)
print(y)
Casting
• x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
• x = "John"
# is the same as
x = 'John'
Case-Sensitive
• x = "awesome"
print("Python is " + x)
• x = "Python is "
y = "awesome"
z= x+y
print(z)
Error
• x=5
y = "John"
print(x + y)
Global Variables
def myfunc():
print("Python is " + x)
myfunc()
• 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.
• x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
The global Keyword
myfunc()
print("Python is " + x)
Python Data Types
• Built-in Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do
different things.
• Python has the following data types built-in by default, in these categories:
• x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
• x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
• x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
• x = 3+5j
• y = 5j
• z = -5j
• print(type(x))
• print(type(y))
• print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
• 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))
• Random Number
• Python does not have a random() function to
make a random number, but Python has a
built-in module called random that can be
used to make random numbers:
• import random
print(random.randrange(1, 10))
Python Casting
• a = "Hello, World!"
print(a[1])
• for x in "banana":
• print(x)
String Length
• a = "Hello, World!"
print(len(a))
• Check String
• txt = "The best things in life are free!"
print("free" in txt)
• Use it in an if statement:
• txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
• Use it in an if statement:
• 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.
• b = "Hello, World!"
print(b[2:5])
• b = "Hello, World!"
print(b[:5])
• b = "Hello, World!"
print(b[2:])
Negative Indexing
• b = "Hello, World!"
print(b[-5:-2])
• Modify Strings
• a = "Hello, World!"
print(a.upper())
• Lower Case
• a = "Hello, World!"
print(a.lower())
• Remove Whitespace
• a = "Hello, World!"
print(a.replace("H", "J"))
• Split String
• a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
• String Concatenation
• a = "Hello"
b = "World"
c=a+b
print(c)
• a = "Hello"
b = "World"
c=a+""+b
print(c)
Format - Strings
• age = 36
txt = "My name is John, I am " + age
print(txt)
• age = 36
• txt = "My name is John, and I am {}"
• print(txt.format(age))
• quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
You can use index numbers {0} to be sure the
arguments are placed in the correct placeholders:
• quantity = 3
itemno =
price = 49.95675
myorder = "I want to pay {2} dollars for {0}
pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Characters
• Escape Character
• To insert characters that are illegal in a string,
use an escape character.
• An escape character is a backslash \ followed
by the character you want to insert.
• An example of an illegal character is a double
quote inside a string that is surrounded by
double
• Error
• txt = "We are the so-called "Vikings" from the
north.“
x = txt.capitalize()
print (x)
x = txt.casefold()
print(x)
• myTuple = ("John", "Peter", "Vicky")
• x = "#".join(myTuple)
• print(x)
Booleans
• print(10 > 9)
print(10 == 9)
print(10 < 9)
• a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Evaluate Values and Variables
The bool() function allows you to evaluate any value, and
give you True or False in return,
• print(bool("Hello")) return true
print(bool(15)) return true
• x = "Hello"
y = 15
print(bool(x))
print(bool(y))
• Most Values are True
• Almost any value is evaluated to True if it has
some sort of content.
• Any string is True, except empty strings.
• Any number is True, except 0.
• Any list, tuple, set, and dictionary are True,
except empty ones.
• print(bool("abc"))
• print(bool(123))
• print(bool(["apple", "cherry", "banana"]))
• Some Values are False
• In fact, there are not many values that evaluate
to False, except empty values, such as (), [], {}, "", the
number 0, and the value None. And of course the
value False evaluates to False.
• bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Functions can Return a Boolean
• def myFunction() :
return True
print(myFunction())
*******************
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Check if an object is an integer or not:
• x = 200
print(isinstance(x, int))
Operators
• 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.
• 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:
Lists allow duplicate values:
• thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
• List Length
• print(list1)
• print(list2)
• print(list3)
• print(list1)
type()
• Access Items
• List items are indexed and you can access them by
referring to the index number:
• Example
• Example
• Print the last item of the list:
• thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
• 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:
• Example
• This example returns the items from the beginning to, but NOT
including, "kiwi":
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
• By leaving out the end value, the range will go on to the end of the
list:
• Example
• This example returns the items from "cherry" to the end:
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
• Range of Negative Indexes
• Specify negative indexes if you want to start
the search from the end of the list:
• Example
• This example returns the items from "orange"
(-4) to, but NOT including "mango" (-1):
• thislist =
["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[-4:-1])
• Check if Item Exists
• To determine if a specified item is present in a
list use the in keyword:
• 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")
Change List 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"]
thislist.append("orange")
print(thislist)
Insert Items
• List Comprehension
• List comprehension offers a shorter syntax when you
want to create a new list based on the values of an
existing list.
• Example:
• Based on a list of fruits, you want a new list, containing
only the fruits with the letter "a" in the name.
• Without list comprehension you will have to write
a for statement with a conditional test inside:
• Example
• fruits =
["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
• With list comprehension you can do all that
with only one line of code:
• Example
• fruits =
["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
Sort Lists
• Copy a List
• You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and changes
made in list1 will automatically also be made in list2.
• There are ways to make a copy, one way is to use the built-in
List method copy().
• Example
• Make a copy of a list with the copy() method:
• thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
• Another way to make a copy is to use the
built-in method list().
• Example
• Make a copy of a list with the list() method:
• thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Join Lists
for x in list2:
list1.append(x)
print(list1)
• Or you can use the extend() method, which purpose
is to add elements from one list to another list:
• Example
• Use the extend() method to add list2 at the end of
list1:
• list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
List Methods
Tuples
• Ordered
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
• print(tuple1)
• print(tuple2)
• print(tuple3)
A tuple can contain different data types:
• type()
print(x)
Add Items
• Unpacking a Tuple
• When we create a tuple, we normally assign
values to it. This is called "packing" a tuple:
• Example
• Packing a tuple:
• fruits = ("apple", "banana", "cherry")
• But, in Python, we are also allowed to extract the values back into
variables. This is called "unpacking":
• Example
• Unpacking a tuple:
• fruits = ("apple", "banana", "cherry")
print(green)
print(yellow)
print(red)
print(green)
print(yellow)
print(red)
• If the asterix is added to another variable name than the
last, Python will assign values to the variable until the
number of values left matches the number of variables left.
• Example
• Add a list of values the "tropic" variable:
• fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
print(green)
print(tropic)
print(red)
Loop Tuples
print(mytuple)
Tuple Methods
• Tuple Methods
• Python has two built-in methods that you can use on
tuples.
• MethodDescription
count()
• Returns the number of times a specified value occurs
in a tuple
index()
• Searches the tuple for a specified value and returns the
position of where it was found
Sets
• Example
• Create a Set:
• thisset = {"apple", "banana", "cherry"}
print(thisset)
• # Note: the set list is unordered, meaning: the
items will appear in a random order.
print(thisset)
Get the Length of a Set
print(len(thisset))
Set Items - Data Types
• print(set1)
• print(set2)
• print(set3)
A set can contain different data types
• Example
• A set with strings, integers and boolean values:
• set1 = {"abc", 34, True, 40, "male"}
• type()
• From Python's perspective, sets are defined as objects with the
data type 'set':
• <class 'set'>
• Example
• What is the data type of a set?
• myset = {"apple", "banana", "cherry"}
print(type(myset))
• The set() Constructor
• It is also possible to use the set() constructor
to make a set.
• Example
• Using the set() constructor to make a set:
• thisset = set(("apple", "banana", "cherry")) #
note the double round-brackets
print(thisset)
Access Set Items
• 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)
• Change Items
• Once a set is created, you cannot change its
items, but you can add new items.
Add Set Items
• Add Items
• Once a set is created, you cannot change its items, but you
can add new items.
• To add one item to a set use the add() method.
• Example
• Add an item to a set, using the add() method:
• thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Add Sets
thisset.update(tropical)
print(thisset)
Add Any Iterable
thisset.update(mylist)
print(thisset)
Remove Set Items
• 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"}
thisset.remove("banana")
print(thisset)
• Note: If the item to remove does not exist, remove() will raise an error.
discard
• Example
• Remove "banana" by using the discard() method:
• thisset = {"apple", "banana", "cherry"}
thisset.discard("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 the last item. Remember that sets are
unordered, so you will not know what item that gets removed.
• The return value of the pop() method is the removed item.
• Example
• Remove the last item by using the pop() method:
• thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
• Note: Sets are unordered, so when using the pop() method, you do
not know which item that gets removed.
• Example
• The clear() method empties the set:
• thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
• Example
• The del keyword will delete the set completely:
• thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
Loop Sets
• 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)
Join Sets
set3 = set1.union(set2)
print(set3)
• Example
• The update() method inserts the items in set2
into set1:
• set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
• Note: Both union() and update() will exclude
any duplicate items.
Keep ONLY the Duplicates
x.intersection_update(y)
print(x)
• The intersection() method will return a new set, that
only contains the items that are present in both sets.
• Example
• Return a set that contains the items that exist in
both set x, and set y:
• x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
Keep All, But NOT the Duplicates
x.symmetric_difference_update(y)
print(x)
• The symmetric_difference() method will return a
new set, that contains only the elements that are
NOT present in both sets.
• Example
• Return a set that contains all items from both sets,
except items that are present in both:
• x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Set Methods
Dictionaries
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
• Changeable
• Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
• 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"]
• There is also a method called get() that will
give you the same result:
• Example
• Get the value of the "model" key:
• x = thisdict.get("model")
Get Keys
x = car.keys()
car["color"] = "white"
x = car.values()
car["year"] = 2020
• Add a new item to the original dictionary, and see that the values list gets
updated as well:
• car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["color"] = "red"
x = car.items()
car["year"] = 2020
x = car.items()
car["color"] = "red"
• 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.
• The argument must be a dictionary, or an iterable object with
key:value pairs.
• Example
• Update the "year" of the car by using the update() method:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Add Dictionary Items
• 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.
• The argument must be a dictionary, or an iterable object with
key:value pairs.
• Example
• Add a color item to the dictionary by using the update() method:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Remove Dictionary Items
• 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
}
thisdict.pop("model")
print(thisdict)
Example
• 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().
• Example
• Make a copy of a dictionary with the copy() method:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
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
• Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested dictionaries.
• Example
• Create a dictionary that contain three dictionaries:
• myfamily = {
"child1" : {
"name" : ”Ajay”,
"year" : 2004
},
"child2" : {
"name" : ”Vijay",
"year" : 2007
},
"child3" : {
"name" : “Rahul",
"year" : 2011
}
}
• Or, if you want to add three dictionaries into a new dictionary:
• Example
• Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:
• child1 = {
"name" : ”Ajay",
"year" : 2004
}
child2 = {
"name" : “Vijay",
"year" : 2007
}
child3 = {
"name" : “Rahul",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Dictionary Methods
If ... Else
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
The pass Statement
if b > a:
pass
While Loops
• 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.
• Example
• Print each fruit in a fruit list:
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
• With the break statement we can stop the loop before it has
looped through all the items:
• Example
• Exit the loop when x is "banana":
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
for x in adj:
for y in fruits:
print(x, y)
The pass Statement
my_function()
Arguments
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
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:
• Error program
• def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Arbitrary Arguments, *args
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
my_function(fruits)
Return Values
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement
• 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))
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]
• 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)
• 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:
• cars.append("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:
• cars.pop(1)
• You can also use the remove() method to
remove an element from the array.
• Example
• Delete the element that has the value "Volvo":
• cars.remove("Volvo")
Array Methods
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
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
• Note: The __init__() function is called automatically every time
the class is being used to create a new object
Object Methods
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
• 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
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
• Modify Object Properties
• You can modify properties on objects like this:
• Example
• Set the age of p1 to 40:
• p1.age = 40
Example
• class Person:
• def __init__(self, name, age):
• self.name = name
• self.age = age
• def myfunc(self):
• print("Hello my name is " + self.name)
• p1 = Person("John", 36)
• p1.age = 40
• print(p1.age)
Delete Object Properties
• def myfunc(self):
• print("Hello my name is " + self.name)
• p1 = Person("John", 36)
• del p1.age
• print(p1.age)
Delete Objects
• def myfunc(self):
• print("Hello my name is " + self.name)
• p1 = Person("John", 36)
• del p1
• print(p1)
The pass Statement
• 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):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class
• def printname(self):
• print(self.firstname, self.lastname)
• class Student(Person):
• pass
• x = Student("Mike", "Olsen")
• x.printname()
Add the __init__() Function
• def printname(self):
• print(self.firstname, self.lastname)
• class Student(Person):
• def __init__(self, fname, lname):
• Person.__init__(self, fname, lname)
• x = Student("Mike", "Olsen")
• x.printname()
• 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 Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()
• 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.
Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
x = Student("Mike", "Olsen")
print(x.graduationyear)
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 Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
• 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
print(next(myit))
print(next(myit))
print(next(myit))
Example
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Create an Iterator
• 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 to go 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 Modules
• What is a Module?
• 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.
• Create a Module
• To create a module just save the code you
want in a file with the file extension .py:
Example
mymodule.greeting("Jonathan")
• Note: When using a function from a module, use
the syntax: module_name.function_name.
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 mymodule.py
• person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Use
• Example
• Import the module named mymodule, and access the person1 dictionary:
• import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
• You can name the module file whatever you like, but it
must have the file extension .py
• Re-naming a Module
• You can create an alias when you import a module, by
using the as keyword:
• Example
• Create an alias for mymodule called mx:
• import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
• There are several built-in modules in Python,
which you can import whenever you like.
• Example
• Import and use the platform module:
• import platform
x = platform.system()
print(x)
Using the dir() Function
• There is a built-in function to list all the function names (or
variable names) in a module. The dir() function:
• Example
• List all the defined names belonging to the platform
module:
• import platform
x = dir(platform)
print(x)
• Note: The dir() function can be used on all modules, also
the ones you create yourself.
Import From Module
• You can choose to import only parts from a module, by using
the from keyword.
• Example
• The module named mymodule has one function and one
dictionary:
• def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
• Import only the person1 dictionary from the
module:
from mymodule import person1
print (person1["age"])
• Note: When importing using the from keyword, do
not use the module name when referring to
elements in the module.
Example: person1["age"], not mymodule.person1["
age"]
Python Datetime
x = datetime.datetime.now()
print(x)
Date Output
• When we execute the code from the example above the result will be:
• 2021-05-04 16:19:18.317711The date contains year, month, day, hour,
minute, second, and microsecond.
• The datetime module has many methods to return information about the date
object.
• Here are a few examples, you will learn more about them later in this chapter:
• Example
• Return the year and name of weekday:
• import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Creating Date Objects
• To create a date, we can use the datetime() class (constructor) of
the datetime module.
• The datetime() class requires three parameters to create a date: year,
month, day.
• Example
• Create a date object:
• import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
• The datetime() class also takes parameters for time and timezone (hour,
minute, second, microsecond, tzone), but they are optional, and has a
default value of 0, (None for timezone).
The strftime() Method
• The datetime object has a method for formatting date objects
into readable strings.
• The method is called strftime(), and takes one
parameter, format, to specify the format of the returned string:
• Example
• Display the name of the month:
• import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Python Math
• Python has a set of built-in math functions, including an
extensive math module, that allows you to perform
mathematical tasks on numbers.
• Built-in Math Functions
• The min() and max() functions can be used to find the lowest
or highest value in an iterable:
• Example
• x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
• The abs() function returns the absolute (positive) value of
the specified number:
• Example
• x = abs(-7.25)
print(x)
• The pow(x, y) function returns the value of x to the power of
y (xy).
• Example
• Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
• x = pow(4, 3)
print(x)
The Math Module
• Python has also a built-in module called math, which extends the list of
mathematical functions.
• To use it, you must import the math module:
• import math
• When you have imported the math module, you can start using methods
and constants of the module.
• The math.sqrt() method for example, returns the square root of a number:
• Example
import math
x = math.sqrt(64)
print(x)
The math.ceil() method
• rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to
its nearest integer, and returns the result:
• Example
• import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
• The math.pi constant, returns the value of PI
(3.14...):
• Example
• import math
x = math.pi
print(x)
Python 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.
• Exception Handling
• When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
• These exceptions can be handled using the try statement:
• 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
if x < 0:
raise Exception("Sorry, no numbers below zero")
• The raise keyword is used to raise an exception.
• You can define what kind of error to raise, and
the text to print to the user.
• Example
Raise a TypeError if x is not an integer:
x = "hello"
• Delete a File
• To delete a file, you must import the OS
module, and run its os.remove() function:
• Example
• Remove the file "demofile.txt":
• import os
os.remove("demofile.txt")
Check if File exist: