IS231: Web Technology
Python
By: Neamat El Tazi
References
- W3Schools - Python
2 Web Technology Neamat El Tazi
Python Operators
Python divides the operators in the following
groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
3 Web Technology Neamat El Tazi
Python Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
4 Web Technology Neamat El Tazi
Python Assignment Operators
Operator Example Same As
= 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
&= 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
5 Web Technology Neamat El Tazi
Python Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
6 Web Technology Neamat El Tazi
Python Logical Operators
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
7 Web Technology Neamat El Tazi
Python 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:
Operator Description Example
is Returns True if both x is y
variables are the same
object
is not Returns True if both x is not y
variables are not the same
object
8 Web Technology Neamat El Tazi
Python Membership Operators
Membership operators are used to test if a
sequence is presented in an object:
Operator Description Example
in Returns True if a sequence x in y
with the specified value is
present in the object
not in Returns True if a sequence x not in y
with the specified value is
not present in the object
9 Web Technology Neamat El Tazi
Python bitwise Operators
Bitwise operators are used to compare
(binary) numbers:
Oper Name Description
ator
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill Shift left by pushing zeros in from the right and let the
left shift leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in from the
right shift left, and let the rightmost bits fall off
10 Web Technology Neamat El Tazi
Python Collections (Arrays)
There are four collection data types in the Python programming
language:
List is 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 and unindexed. No duplicate
members.
Dictionary is a collection which is unordered 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.
11 Web Technology Neamat El Tazi
Python Lists
Lists are used to store multiple items in a single variable.
Lists are created using square brackets:
thislist = ["apple", "banana", "cherry"]
print(thislist)
12 Web Technology Neamat El Tazi
List Items
List items are ordered, changeable, and allow duplicate
values.
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.
13 Web Technology Neamat El Tazi
List Items
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:
14 Web Technology Neamat El Tazi
List Functions
List Length
Len()
Constructor
List()
thislist = list(("apple", "banana", "cherry")) #
note the double round-brackets
print(thislist)
Insert
thislist.insert(2,”watermelon”)
Append
thislist.append(“orange”)
15 Web Technology Neamat El Tazi
List Functions
Extend List
To append elements from another list to the
current list, use the extend() method
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
Add Any Iterable
The extend() method does not have to
append lists, you can add any iterable object
(tuples, sets, dictionaries etc.).
16 Web Technology Neamat El Tazi
List Functions
Remove
The remove() method removes the specified
item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
Remove Specified Index
The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
If you do not specify the index, the pop() method removes the last
item
17 Web Technology Neamat El Tazi
.
List Functions
The del keyword can also delete the list completely.
thislist = ["apple", "banana", "cherry"]
del thislist
It can also deletes the specified index
del thislist[1]
The clear() method empties the list.
The list still remains, but it has no content
18 Web Technology Neamat El Tazi
List Functions
Sort List
thislist.sort()
thislist.sort(reverse = True)
thislist.sort(key=str.lower) #perform a case-sensitive sort
Copy 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.
Mylist = thislist.copy()
Mylist = list(thislist)
19 Web Technology Neamat El Tazi
Change List Items
To change the value of a specific item, refer to
the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
20 Web Technology Neamat El Tazi
Change a Range of Item Values
To change the value of items within a specific
range, define a list with the new values, and refer
to the range of index numbers where you want to
insert the new values:
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"]
21 Web Technology Neamat El Tazi
Loop Through a List
You can loop through the list items by using a for loop:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
A shorthand for loop that will print all items
in a list using list comprehension:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
22 Web Technology Neamat El Tazi
List Comprehension
List comprehension offers a shorter syntax
when you want to create a new list based on
the values of an existing list.
Without list comprehension With list comprehension
fruits = fruits =
["apple", "banana", "cherry", ["apple", "banana", "cherry", "
"kiwi", "mango"] kiwi", "mango"]
newlist = []
newlist =
for x in fruits: [x for x in fruits if "a" in x]
if "a" in x:
newlist.append(x) print(newlist)
print(newlist)
23 Web Technology Neamat El Tazi
List Comprehension Syntax
newlist =
[expression for item in iterable if conditio
n == True]
The return value is a new list, leaving the old
list unchanged.
24 Web Technology Neamat El Tazi
Python 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.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
25 Web Technology Neamat El Tazi
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.
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
26 Web Technology Neamat El Tazi
Tuple Items - Data Types
Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
tuple1 = ("abc", 34, True, 40, "male")
27 Web Technology Neamat El Tazi
The tuple() Constructor
It is also possible to use
the tuple() constructor to make a tuple.
thistuple =
tuple(("apple", "banana", "cherry")) # note
the double round-brackets
print(thistuple)
28 Web Technology Neamat El Tazi
Access Tuple Items
You can access tuple items by referring to the
index number, inside square brackets:
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Negative Indexing:
Negative indexing means start from the end.
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
29 Web Technology Neamat El Tazi
Check if Item Exists
To determine if a specified item is present in a tuple use
the in keyword:
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits
tuple")
30 Web Technology Neamat El Tazi
Update Tuples
Once a tuple is created, you cannot change its
values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the
tuple into a list, change the list, and convert the
list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
31 Web Technology Neamat El Tazi
Pack and Unpack Tuples
When we create a tuple, we normally assign values to
it. This is called "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":
(green, yellow, red) = fruits
The number of variables must match the number of values in the tuple, if not, you must
use an asterix to collect the remaining values as a list.
(green, yellow, *red) = fruits
32 Web Technology Neamat El Tazi
Loop Tuples
Looping in Tuples is the same as Lists
You can use for loop or while loop
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
33 Web Technology Neamat El Tazi
Multiply Tuples
If you want to multiply the content of a tuple a given
number of times, you can use the * operator:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
34 Web Technology Neamat El Tazi
Tuple Functions
Method Description
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
35 Web Technology Neamat El Tazi
Python Sets
Sets are used to store multiple items in a single variable.
A set is a collection which is both unordered and
unindexed.
Sets are written with curly brackets.
myset = {"apple", "banana", "cherry"}
36 Web Technology Neamat El Tazi
Create a Set
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set items are unordered, unchangeable,
and do not allow duplicate values.
In case of duplicate values, they will be
ignored:
thisset =
{"apple", "banana", "cherry", "apple"}
print(thisset)
37 Web Technology Neamat El Tazi
The set() Constructor
It is also possible to use the set() constructor
to make a set.
thisset =
set(("apple", "banana", "cherry")) # note
the double round-brackets
print(thisset)
38 Web Technology Neamat El Tazi
Access Set 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.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("banana" in thisset)
39 Web Technology Neamat El Tazi
Add Items to a Set
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.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
40 Web Technology Neamat El Tazi
Add Set to Another Set
To add items from another set into the current set, use the update()
method.
Add elements from tropical and thisset into newset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
The object in the update() method does not have be a
set, it can be any iterable object (tuples, lists,
dictionaries or sets).
41 Web Technology Neamat El Tazi
Remove Set Items
To remove an item in a set, use the remove(), or the discard()
method.
Remove "banana" by using the
remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
Note: If the item to remove does not exist, remove() will raise an error.
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
Note: If the item to remove does not exist, remove() will NOT raise an error.
42 Web Technology Neamat El Tazi
Remove Set Items
You can also use pop() to remove an item, it will
remove only the last item and that item will be
returned in the result.
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
Remember that sets are not indexed so you cannot
use pop with an index number. And since sets are not
ordered, you will not also know which item got
removed!
43 Web Technology Neamat El Tazi
Set Functions
The clear() method empties the set
The del keyword will delete the set completely
The copy() returns a copy of the set
The difference() returns a set containing the
difference between two or more sets.
Check the rest of set functions:
https://www.w3schools.com/python/python_sets
_methods.asp
44 Web Technology Neamat El Tazi
Python Dictionaries
Dictionaries are used to store data values in
key:value pairs.
A dictionary is a collection which is unordered,
changeable and does not allow duplicates.
Dictionaries are written with curly brackets, and
have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
45 Web Technology Neamat El Tazi
Dictionary Items
Dictionary items are presented in key:value
pairs, and can be referred to by using the key
name.
Unordered
When we say that dictionaries are unordered, it means
that the items does not have a defined order, you cannot
refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key. Duplicate values
will overwrite existing values
46 Web Technology Neamat El Tazi
Duplicate values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
# will return
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
47 Web Technology Neamat El Tazi
Dictionary Length
To determine how many items a dictionary has, use the
len() function:
print(len(thisdict))
48 Web Technology Neamat El Tazi
Dictionary Items - Data Types
The values in dictionary items can be of any
data type:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
49 Web Technology Neamat El Tazi
Accessing Items
You can access the items of a dictionary by
referring to its key name, inside square
brackets:
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
50 Web Technology Neamat El Tazi
Accessing Items
There is also a method called get() that will
give you the same result:
x = thisdict.get("model")
51 Web Technology Neamat El Tazi
Get Keys
The keys() method will return a list of all the keys in the
dictionary.
x = thisdict.keys()
The list of the keys is a view of the dictionary,
meaning that any changes done to the
dictionary will be reflected in the keys list.
52 Web Technology Neamat El Tazi
Get Keys Example
Add a new item to the original dictionary, and see
that the keys list gets updated as well
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
53 Web Technology Neamat El Tazi
Get Values
The values() method will return a list of all the values in
the dictionary.
x = thisdict.values()
54 Web Technology Neamat El Tazi
Get Items
The items() method will return each item in a dictionary,
as tuples in a list.
Get a list of the key:value pairs
x = thisdict.items()
#will return:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
2020)])
55 Web Technology Neamat El Tazi
Check if Key Exists
To determine if a specified key is present in a dictionary
use the in keyword:
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
56 Web Technology Neamat El Tazi
Change Dictionary Items
Change Values
You can change the value of a specific item by referring to its key
name
Change the "year" to 2018:
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
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
57 Web Technology Neamat El Tazi
Add Dictionary Items
Adding an item to the dictionary is done by
using a new index key and assigning a value
to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
58 Web Technology Neamat El Tazi
Adding items using update
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:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
59 Web Technology Neamat El Tazi
Remove Dictionary Items
The pop() method removes the item with the specified
key name:
thisdict.pop("model")
The popitem() method removes the last inserted item (in
versions before 3.7, a random item is removed instead):
thisdict.popitem()
The clear() method empties the dictionary
The del keyword removes the item with the specified key
name:
del thisdict["model"]
The del keyword can also delete the dictionary
completely
60 Web Technology Neamat El Tazi
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the
keys of the dictionary, but there are methods to return the
values as well.
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
61 Web Technology Neamat El Tazi
Loop Through a Dictionary
You can also use the values() method to return values of
a dictionary:
for x in thisdict.values():
print(x)
You can use the keys() method to return the keys of a
dictionary:
for x in thisdict.keys():
print(x)
Loop through both keys and values, by
using the items() method:
for x, y in thisdict.items():
print(x, y)
62 Web Technology Neamat El Tazi
Copy Dictionaries
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()
63 Web Technology Neamat El Tazi
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested
dictionaries.
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
64 Web Technology Neamat El Tazi
Nested Dictionaries
Create three dictionaries, then create one dictionary that will
contain the other three dictionaries
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
65 Web Technology Neamat El Tazi
Python Conditions and If statements
An "if statement" is written by using
the if keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
66 Web Technology Neamat El Tazi
Python Conditions and If statements
The elif keyword is python’s way of saying "if
the previous conditions were not true, then
try this condition“
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
67 Web Technology Neamat El Tazi
Python Conditions and If statements
The else keyword catches anything which isn't
caught by the preceding conditions.
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")
68 Web Technology Neamat El Tazi
Python Conditions and If statements
You can also have an else without the elif:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
69 Web Technology Neamat El Tazi
Short Hand If
If you have only one statement to execute,
you can put it on the same line as the if
statement.
if a > b: print("a is greater than b")
70 Web Technology Neamat El Tazi
Ternary Operators, or Conditional Expressions
If you have only one statement to execute,
one for if, and one for else, you can put it all
on the same line
a = 2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on
the same line
print("A") if a > b else print("=") if a ==
b else print("B")
71 Web Technology Neamat El Tazi
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.
a = 33
b = 200
if b > a:
pass
72 Web Technology Neamat El Tazi
Loops
Go through while loops in
https://www.w3schools.com/python/python_while_loops.as
p
Go through for loops in:
https://www.w3schools.com/python/python_for_loops.asp
73 Web Technology Neamat El Tazi
Functions
In Python a function is defined using
the def keyword:
def my_function():
print("Hello from a function")
74 Web Technology Neamat El Tazi
Number of Arguments
By default, a function must be called with the
correct number of arguments. Meaning that if
your function expects 2 arguments, you have
to call the function with 2 arguments, not
more, and not less.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error
75 Web Technology Neamat El Tazi
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:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
76 Web Technology Neamat El Tazi
Keyword Arguments
You can also send arguments with
the key = value syntax.
This way the order of the arguments does not
matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2
= "Tobias", child3 = "Linus")
77 Web Technology Neamat El Tazi
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that
will be passed into your function, add two asterisk: **
before the parameter name in the function definition.
This way the function will receive a dictionary of
arguments, and can access the items accordingly
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
78 Web Technology Neamat El Tazi
Lambda Function
A lambda function is a small anonymous function.
A lambda function can take any number of
arguments, but can only have one expression.
Syntax
lambda arguments : expression
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
79 Web Technology Neamat El Tazi