Session 2
Session 2
Python
Session 2
Ahmed Elaraby 1
Tuples
• A tuple is a collection which is ordered and unchangeable In Python tuples are
written with round brackets.
• You can access tuple items by referring to the index number, inside square
brackets.
• You can specify a range of indexes by specifying where to start and where to end
the range.
• When specifying a range, the return value will be a new tuple with the specified
items.
Ahmed Elaraby 2
• thistuple = ("apple", "banana", "cherry")
• print(thistuple)
• >>> ('apple', 'banana', 'cherry')
• >>> thistuple = ("apple",)
• 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)
• print(x) >>> ("apple", "kiwi", "cherry")
• Add Items:
• y = list(x)
• y.append("orange")
• thistuple = tuple(y)
• Add tuple to a tuple:
• thistuple += y
• Remove Items:
• y = list(thistuple)
• y.remove("apple")
• thistuple = tuple(y)
• del thistuple Ahmed Elaraby 4
Tuple Methods
Method Description
Returns the number of times a specified value occurs
count()
in a tuple
Searches the tuple for a specified value and returns
index()
the position of where it was found
Ahmed Elaraby 5
Sets
• A set is a collection which is unordered and unindexed In Python sets are written with curly
brackets.
• You cannot access items in a set by referring to an index, since sets are unordered the items has
no index.
• But you can loop through the set items.
• thisset = {"apple", "banana", "cherry"}
• for x in thisset:
print(x)
• Once a set is created, you cannot change its items, but you can add new items.
• thisset = {"apple", "banana", "cherry"}
• print(thisset)
• print(len(thisset))
• print(type(thisset))
• thisset = set(("apple", "banana", "cherry"))
Ahmed Elaraby 6
• To add one item to a set use the add() method.
• thisset = {"apple", "banana", "cherry"}
• thisset.add("orange")
• print(thisset)
• To add items from another set into the current set, use the update() method.
• thisset = {"apple", "banana", "cherry"}
• tropical = {"pineapple", "mango", "papaya"}
• thisset.update(tropical)
• print(thisset)
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict) >>> {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
print(thisdict["brand"]) >>> Ford
print(len(thisdict)) >>> 3
print(type(thisdict)) >>> <class 'dict'>
thisdict["year"] = 2018
Ahmed Elaraby 10
• Dictionaries cannot have two items with the same key.
• There is also a method called get() that will get item by key.
• x = thisdict.get("model")
• The keys() method will return a list of all the keys in the dictionary.
• x = thisdict.keys()
• The values() method will return a list of all the values in the dictionary.
• x = thisdict.values()
• The items() method will return each item in a dictionary, as tuples in a list.
• x = thisdict.items()
• 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) Ahmed Elaraby 13
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist: insert the key,
setdefault()
with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Ahmed Elaraby 14
Arithmetic Operators
Ahmed Elaraby 15
Assignment Operators
Ahmed Elaraby 16
Logical Operators
or Logical OR If any of the two operands are non zero, then the
condition is true.
and Logical AND If both the operands are true, then the condition
is true.
not Logical NOT It is used to reverse the logical state of its
operand.
Ahmed Elaraby 17
logical conditions
Ahmed Elaraby 18
Membership Operators
• In
• The result of this operation becomes True if it finds a value in a specified
sequence and False otherwise.
• Not in
• The result of this operation becomes True if it doesn't find a value in a
specified sequence and False otherwise.
Ahmed Elaraby 19
Decision making
• Python Conditions and If statements :
• These conditions can be used in several ways, most commonly in "if statements" and loops.
• An "if statement" is written by using the if keyword.
• a = 33
• b = 200
• if b > a:
print("b is greater than a")
• Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
Other programming languages often use curly-brackets for this purpose.
• The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".
• if b > a:
print("b is greater than a")
• elif a == b:
print("a and b are equal")
• The else keyword catches anything which isn't caught by the preceding conditions.
• else:
print("a is greater than b") Ahmed Elaraby 20
• 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")
• 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")
Ahmed Elaraby 22
While Loops
• With the while loop we can execute a set of statements as long as a condition is true.
• i=1
• while i < 6:
print(i)
i += 1
• The while loop requires relevant variables to be ready, in this example we need to define an indexing
variable, i, which we set to 1.
• With the break statement we can stop the loop even if the while condition is true:
• i=1
• while i < 6: 1
print(i)
if i == 3:
2
break 3
i += 1
• With the continue statement we can stop the current iteration, and continue with the next:
• i=0
• while i < 6: 1
i += 1 2
if i == 3: 4
continue 5
print(i)
6 Ahmed Elaraby 23
• With the else statement we can run a block of code once when the
condition no longer is true:
• i=1
• while i < 6: 1
print(i) 2
3
i += 1 4
• else: 5
print("i is no longer less than 6") i is no longer less than 6
Ahmed Elaraby 24
For Loops
• A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string).
• Anything in a sequence or list can be used in a For loop.
• Just be sure not to modify the list while looping.
• fruits = ["apple", "banana", "cherry"]
apple
• for x in fruits: banana
print(x) cherry
• Break the loop when x is 3, and see what happens with the else block:
• for x in range(6):
if x == 3: 0
break 1
2
print(x)
Ahmed Elaraby 27
Nested Loops
Ahmed Elaraby 28
Functions
• A function is a block of code which only runs when it is called.
• Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
• def my_function(fname):
print(fname + " Refsnes")
• my_function("Emil")
• my_function("Tobias")
Ahmed Elaraby 30
• A parameter is the variable listed inside the parentheses in the function
definition.
• An argument is the value that is sent to the function when it is called.
• 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 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")
Ahmed Elaraby 31
• 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")
• 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")
Ahmed Elaraby 32
• If we call the function without argument, it uses the default value:
• def my_function(country = "Norway"):
print("I am from " + country)
• my_function("India")
• my_function()
• function definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass statement to avoid getting an error.
• def myfunction():
pass
Ahmed Elaraby 33
Recursion
• Python also accepts function recursion, which means a defined function can call
itself.
• Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
• def tri_recursion(k):
1
if(k > 0):
3
result = k + tri_recursion(k - 1)
6
print(result)
10
else:
15
result = 0
21
return result
• tri_recursion(6)
Ahmed Elaraby 34
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.
• x = lambda a : a + 10
• print(x(5))
• x = lambda a, b : a * b
• print(x(5, 6))
Ahmed Elaraby 35