ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Chapter # 7
Introduction to
Python
Programming Language
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 1
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Basics Concepts of Python
• It supports functional and structured programming style as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for
building large applications.
• It can be easily integrated with C, C++, Java …..etc
• Python files have extension .py
• A Python script can be executed at command line by invoking the interpreter on
your application without passing a script file, as following:
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 2
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Basic Python Syntax
• A Python identifier is a name used to identify a variable, function, class, module,
or other object. However, python is case sensitive
• Python variables do not need explicit declaration to reserve memory space
• Python provides no braces to indicate blocks of code for class and function
definitions or flow control such as loops and branchs.
• A single code block are called Suite in Python.
• Compound or complex statements, such as if, while, def, and class require a
header line and a suite.
• The semicolon ( ; ) only needed if you have multiple statements on the single line
• Arithmetic, Logic and Comparison operators are very similar to C`
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 3
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Naming Conventions for Python Identifiers
Python is a case sensitive programming language and does not support
access control (NO access specifiers such as protected in C++ & Java).
Class names start with an uppercase letter. All other identifiers start with
a lowercase letter.
Starting an identifier with a single leading underscore ( _ ) indicates that
the identifier is protected.
Starting an identifier with two leading underscores ( _ _ ) indicates a
strongly private identifier.
If the identifier ends with two trailing underscores, the identifier is a
language-defined special name.
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 4
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Line Indentation & Compound Statement
Header lines, such as “IF”, begin a statement and terminate with a
colon ( : ) and are followed by one or more lines which make up the
suite.
Blocks of code are specified using line indentation. For Example:
if True:
print ("Answer " )
print ("True“)
else:
print ("Answer“)
print ("False“)
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 5
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Input Statement
• Python provides two built-in functions to read a line of text from
standard input (Keyboard):
• input([prompt]) function is equivalent to raw_input, except that
it assumes the input is a valid Python expression and returns
the evaluated result to you.
str = input("Enter your input: ");
print ("Received input is : ", str)
• A hash sign (#) that is not inside a string literal begins a comment
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 6
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Output Format & String Functions
• Output Format can be used very similar to C, Python uses conversion characters such as
%c, %s, %d , %f , %e , %u ….etc. for example:
print ("My name is %s & weight is %d kg!", 'Zara', 21)
• String Functions
Sr. No. Methods with Description
1 capitalize() Capitalizes first letter of string.
2 center(width, fillchar) Returns a space-padded string with the original
string centred to a total of width columns.
3 count(str, beg= 0,end=len(string)) Counts how many times str
occurs in string or in a substring of string if starting index beg and
ending index end are given.
4 isdigit() Returns true if string contains only digits and false otherwise
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 7
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Output Statement & Strings
• Example using command Line
C:\....> Python str = 'Hello World!'
>>>> print ("Hello, Python!“) print (str) # Prints complete string
The output : Hello, Python! print (str[0]) # Prints 1st character
print (str[2:5]) # Print chars from 3rd - 5th
• Example using IDE or *.py file print (str[2:]) # Print string start from 3rd
counter = 100 print (str* 2) # Prints string two times
miles = 1000.0 print (str + "TEST“) # Prints concatenated string
name = "John”
print (counter) The Output
print (miles) Hello World!
print (name) H
The output llo
100 llo World!
1000.0 Hello World!Hello World!
John Hello World!TEST
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 8
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Operators
Python operators are very similar to C
Arithmetic +, - , * , / ,% , ++ , - =, += ..etc
Logic and , or , not
Comparison == , != , < , > , <> , >= ..etc
Member Ship operator
This operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below:
Operator Description Example
in Evaluates to true if it finds a variable in x in y, This returns 1 if x is
a specified sequence and false otherwise. a member of sequence y.
not in Evaluates to true if it does not finds a x not in y, This returns 1 if x
variable in the specified sequence and x is not a member of sequence y.
false otherwise.
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 9
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Example of Membership Operators
a = 10 ; b = 20
list = [1, 2, 3, 4, 5 ];
# If the “if” clause consists only one line, it can be on the same line
if ( a in list ): print("Line 1 - a is available in the given list“)
else: print("Line 1 - a is not available in the given list“)
if ( b not in list ): print("Line 2 - b is not available in the given list“)
else: print("Line 2 - b is available in the given list“)
a=2
if ( a in list ): print("Line 3 - a is available in the given list”)
else: print("Line 3 - a is not available in the given list“)
The OUTPUT
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 10
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Control Statements (for Loop)
• It has the ability to iterate over the items of for i in ‘EC252':
any sequence, such as a list or a string. print('Current Letter :', i)
for iterating_var in sequence: fruits = ['banana', 'apple', 'mango']
statements(s) for j in fruits:
• If a sequence contains an expression list, it is print('Current fruit :', j)
evaluated first. Then, the first item in the The OUTPUT
sequence is assigned to the iterating variable Current Letter : E
iterating_var. Current Letter : C
Current Letter : 2
• Next, the statements block is executed. Current Letter : 5
Current Letter : 2
• Each item in the list is assigned to Current fruit : banana
iterating_var, and the statement(s) block is Current fruit : apple
executed until the entire sequence is Current fruit : mango
exhausted.
EC252-Fall2019 ( Chapter 7) Dr. Youssef Omran Gdura 11
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Function in Python
Functions: The heading (prototype) contains
Keyword def … Function name
Parentheses; and finally a colon.
The syntax of defining a function.
def function_name(parameters):
Statement1
statement2
...
...
return [expr]
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 12
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Functions Examples
Example #1 Example #2
def SayHello() : def SayHello(name) :
print ("Hello! Welcome") print ("Hello {}!.".format(name))
return return
To call the function we write We can call the function as
SayHello()
SayHello(“Ali”)
The output will be
The Output will be
Hello! Welcome Hello Ali
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 13
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Functions (Examples)
def result(m1,m2,m3):
ttl=m1+m2+m3
percent=ttl/3
if percent>=50:
print ("Result: Pass")
else:
print ("Result: Fail")
return
p=int(input("Enter your marks in physics: "))
c=int(input("Enter your marks in chemistry: "))
m=int(input("Enter your marks in maths: "))
result(p,c,m)
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 14
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Pass-by Reference
In Python, arguments are always passed by reference. For
example:
def myfunction (list) :
list.append(40)
print ("Modified list inside a function: ", list)
return
The following statements tests the above function:
>>> mylist=[10,20,30]
>>> myfunction(mylist)
Modified list inside a function: [10, 20, 30, 40]
>>> mylist
[10, 20, 30, 40]
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 15
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Functions Arguments
Arbitrary Arguments: 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.
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Default Argument Value
def my_function(country = “Libya"):
print("I am from " + country)
my_function("Sweden") I am from Sweden
my_function() I am from Libya
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 16
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Library Functions: sinh(x)
The problem is solve the sinh(x) function: Solving sinh(x) in Python
// Python program
sinh(x) = ½ ( e x - e –x ) from math import sinh, exp, e, pi
x = 2 * pi
w1 = sinh(x) # 1st way
We can evaluate sinh (x) in three ways: w2 = 0.5*(exp(x) - exp(-x)) # 2nd way
i) Calling math.sinh, w3 = 0.5*(e**x - e**(-x)) # 3rd way
ii) Computing the right-hand side using print(w1, w2, w3)
math.exp
iii) Computing the right-hand side using OUTPUT
the power expressions math.e**x and
math.e**(-x). 267.744894 267.744894 267.744894
EC252-Fall2019 ( Chapter 7 ) Dr. Youssef Omran Gdura 17
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Chapter # 8
Python
Data Types (Structures)
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 18
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
New Data Types (Structures) in Python
• Lists
• Arrays
• Tuples
• Sets
• Dictionaries
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 19
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Lists in Python
• Lists are the most flexible Python's compound data types.
• Python’s lists are similar to arrays in C, BUT python list can be of different data
type.
• Items are separated by commas and enclosed within square brackets ([ ])
• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting from 0 till end-1
Example
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john'] The OUTPUT
print (list) # complete list ['abcd', 786, 2.23, 'john', 70.2]
print(list[0]) # first element list abcd
print(list[1:3]) # 2nd & 3th elements (4th no) [786, 2.23]
print(list[2:]) # 3rd element and upward [2.23, 'john', 70.2]
print(tinylist * 2) # Prints list two times [123, 'john', 123, 'john']
print(list + tinylist) # Prints concatenated lists ['abcd', 786, 2.23, 'john', 70.2, 123,
'john']
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 20
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Loops over List in Python
• EXAMPLE
list1 = ['physics', 'chemistry', 1997, 2000];
for obj in list1: print(obj)
The OUTPUT
physics
chemistry
1997
2000
list1 = ['physics', 'chemistry', 1997, 2000];
for obj in enumerate(list1): print(obj)
The OUTPUT
(0, 'physics')
(1, 'chemistry')
(2, 1997)
(3, 2000
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 21
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Deleting Elements from a List
• To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting.
EXAMPLE
list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)
del list1[2]
print("After deleting value at index 2 : " )
print(list1)
The OUTPUT
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 22
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Library Functions on List
Function Description
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
EXA MPLE
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200] The OUTPUT
print("Max value element : ", max(list1)) Max value element : zara
print("Max value element : ", max(list2))
print("min value element : ", min(list1))
Max value element : 700
print("min value element : ", min(list2))
min value element : 123
min value element : 200
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 23
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Library Functions on List
Function Description
append(…) add item to the end of the list
extend(list) add contents of one list to another
sum(List) calculate sum of elements (Numeric values) in a list
EXAMPLE
list1, list2 = [1, 'x', 'a', 'a'], [4, 7, 2]
list1.append(“EC251”)
print(list1) [1, 'x', 'a', 'a', 'EC251']
Print(sum(list2) 13
List2.extend(list1)
Print(list2) [4, 7, 2, 1, 'x', 'a', 'a', 'EC251']
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 24
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Problem Answer in C++
Remove duplicated numbers from the a int list[10]={2, 5, 3, 5 ,6, 4, 2, 8, 6, 4 };
given list int NewList[10], NLIndex=0;
bool foundflg=false;
for (int I = 0 ; i < 10 ; i++) {
Answer in Python foundflg = false;
list = [2, 5, 3, 5 ,6, 4, 2, 8, 6, 4 ] for(int j = 0 ; j < NLIndex ; j++) {
NewList=[ ] if ( list[ i ] == NewList[ j ]) {
foundflg = true;
for j in list: break;
if ( j not in NewList ): }
NewList.append( j ) }
print(NewList) if ( foundflg == false ) {
NewList[ NLIndex ] = list[ i ];
OUTPUT NLIndex++;
[2, 5, 3, 6, 4, 8] }
}
for (int j = 0; j < NLIndex; j++)
cout << NewList[j] << "\t";
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 25
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Arrays in Python
Python does not have built-in support for Arrays, but Python Lists can be
used instead.
Great an Array:
cars = ["Ford", "Volvo", "BMW"]
• Loop through array
for x in cars: print(x)
• Adding an element
cars.append("Honda")
• Removing array element
cars.pop(1) // remove second element
OR cars.remove("Volvo")
EC252-Fall2019 ( Chapter 8 ) Dr. Youssef Omran Gdura 26
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Arrays in Python
Python does not have built-in support for Arrays, but Python Lists can be
used instead.
Assume that we have L=[“a”, “c”, “b”]
Insert element:
L . insert(1,”x”) =[“a”, “x”,“c”, “b”]
• Sort Array
L . sort () =[“a”, “b”,“c”, “x”]
• Reverese array
L . reverse() =[“x”, “c”,“b”, “a”]
EC252-Fall2019 ( Chapter 8 ) Dr. Youssef Omran Gdura 27
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Functions on Arrays
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
reverse() Reverses the order of the list
sort() Sorts the list
EC252-Fall2019 ( Chapter 8 ) Dr. Youssef Omran Gdura 28
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Tuples
• A tuple is a sequence of immutable Python objects.
• Tuples are sequences, just like lists, BUT tuples cannot be changed
• Tuples use parentheses (), whereas lists use square brackets [ ].
1- Access tuples
thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) == banana
2- Negative indexing (means beginning from the end, -1 refers to the
last item, -2 refers to the second last item etc.)
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1]) = charry
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 29
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Tuples
3- Range of indexs
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon")
print( thistuple[2:5]) ('cherry', 'orange', 'kiwi')
4- Change Tuple Values
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")
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 30
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Tuples
6- Loops on tuples
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
7- Check if Item exist
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
8- Joint two tuples
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 31
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Functions (Methods) on Tuples
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
tuple1 = ("a", "b" , "c")
tuple1.count(‘a’) 1
tuple1.index(‘a’) 0
tuple1.index(‘c’) 2
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 32
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Problem (Using Negative index in C++)
class Array { int main() {
float arr[10]; Array A1;
public: cout << A1[2] << "\t" << A1[-2] << endl;
Array() { return 0;
for(int i = 0 ; i < 10; i++) }
arr[ I ] = i;
}
float& operator[] (int index ) {
if ( index < 0 ) // In Case Negative
index=10+index;
return arr [ index ];
}
};
EC252-Fall2019 ( Chapter 8 ) Dr. Youssef Omran Gdura 33
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Sets
• A set is a collection which is unordered and unindexed.
• Sets are written with curly brackets { } , Tuples use parentheses ( )
whereas lists use square brackets [ ].
• You cannot access items in a set by referring to an index, But you can
loop through the set items using a for loop
1- Access tuples
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
2- Check if Item exist
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset) = true
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 34
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Sets
3- Add One Item to a set (at the beginning of the set)
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
4- Add multiple Items to a set
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
Output : {'mango', 'cherry', 'orange', 'apple', 'banana', 'grapes'}
5- Remove last Item from a set
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x) charry
print(thisset) {'banana', 'apple'}
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 35
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Sets Methods (functions)
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 36
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Dictionaries
• Python's dictionaries consist of key-value pairs such as associative arrays
• A dictionary key can be any Python type, but are usually numbers or strings.
• Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
tinydict = {'name': 'john','code':6734, 5: ‘You'} The OUTPUT
print(tinydict[5]) # print(value of key 5 You
print(tinydict) # complete dictionary {'name': 'john', 'code': 6734, 5: 'You'}
print(tinydict.keys()) # Prints all the keys ['name', 'code', 5]
print(tinydict.values()) # Prints all the values ['john', 6734, 'You']
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 37
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Dictionaries
dict = {'name': 'john','code':6734, 5: ‘You'}
1- get() : print(dict.get("code")) 6734
2- change item
dict["name"] = "Ali“ {'name': 'Ali', 'code': 6734, 5: 'You'}
3 Loop on dictionary
for i in dict: print(i) // print only the keys
for i in dict: print(dict[ i ]) // print only the values
4- Use Items to get keys and value // THE OUTPUT
for i , j in dict . items(): print( i , j ) name Ali
code 6734
5 You
EC252-Fall2019 ( Chapter 8) Dr. Youssef Omran Gdura 38
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Chapter # 9
Classes
Python
EC252-Fall2019 ( Chapter 9) Dr. Youssef Omran Gdura 39
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Reviewing OO Concepts in C++
A class contains data members and member functions
A class, similar to Struct, is heterogeneous structure (different types at a time ).
Object can be used the same way AS variables or arrays of built-in data type
Example Assume we have a class called Car, we then can declare the following:
Car X; // X is scalar object (or variable) of type car
Car Y[10] ; // Y is array of objects of type car
Car *Z ; // Z is a pointer to an object of type car
In C++, there three members access specifies: Public, Private and Protected
Member of class can be accessed using:
Object and direct access operator (.) such as X . Display();
Pointer and arrow symbol () such as ZDisplay();
EC252-Fall2019 ( Chapter 5 ) Dr. Youssef Omran Gdura 40
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Class Definition in Python
Class :
class ClassName: # class Name must start with class
definition ( or class suite) # capital letter
Constructor: Only one constructor that defines and initializes data members
def _ _init_ _ ( self , argument list ) :
constructor body
Destructor: i def _ _del_ _ ( ):
destructor-body,
Data member must be accessed via the special self parameter
Class Identifier
EC252-Fall2019
function Id() : returns
( Chapter 9 )
unique identifier (ID) of a given
Dr. Youssef Omran Gdura 41
object. It is similar to pointers in C++
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Build-in Class Attributes
Every Python class has 3 main built-in attributes and they
can be accessed using dot operator like any other attribute
1. Class documentation string or none, if undefined.
_ _doc_ _:
2. Class name.
_ _name_ _:
3. Tuple containing base classes in the order of their occurrence in the
base class list. It is possibly empty.
_ _bases_ _:
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 42
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Example (Classes)
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
x = self.__class__.__name__
print(x, "destroyed“)
pt1 = Point()
pt2 = pt1 ; pt3 = Point()
print(id(pt1), id(pt2), id(pt3))
del pt1 ; del pt2 Output
45952712 45952712 45952832
Point destroyed
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 43
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Example Using Build-in Class Attributes
class Employee: E1 = Employee("Zara",2000)
'My class Employee in Python' E2 = Employee("Fatema",2400)
empCount = 0 E2.displayCount()
def __init__(self, name, salary): E2.displayEmployee()
self.name = name print("Employee.__doc__:", Employee.__doc__)
self.salary = salary print("Employee.__name__:", Employee.__name__)
Employee.empCount +=1 print("Employee.__bases__:", Employee.__bases__)
def displayCount(self): OUTPUT
print("Total Employee %d“, Total Employee 2
Employee.empCount) Name : Fatema , Salary: 2400
def displayEmployee(self): Employee.__doc__: My class Employee in Python
print("Name : ", self.name Employee.__name__: Employee
Salary: ", self.salary) Employee.__bases__: ()
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 44
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Class Inheritance
Derived classes are declared like a base class with a list of base classes after
the class name:
Syntax :
class DerivedClassName ( BaseClass1 , BaseClass2 , … ) :
'Optional class documentation string'
class_suite
Example:
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 45
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Class Inheritance
Example:
class Parent: # define parent class c = Child() # instance of child
parentAttr = 100 c.childMethod()
def __init__(self): c.getAttr()
print("Calling parent constuctor“) c.parentMethod()
def parentMethod(self): c.setAttr(200)
print('Calling parent function' ) c.getAttr()
def setAttr(self, attr):
Parent.parentAttr = attr ) OUTPUT
def getAttr(self): Calling child constructor
print(Parent.parentAttr) 100
class Child(Parent): # define child class Calling child function
def __init__(self): Calling parent function
print("Calling child constructor“) Parent attribute : 200
def childMethod(self):
print(“Calling child function” )
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 46
Access Specifiers
Python does NOT have any mechanism that restricts access to
any data or functions.
So, all members ib a Python class are public by default
Python uses prefixing name (data or function) with single ( _ ) or
double ( _ _ ) underscore to emulate protected and private
access specifiers respectively.
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 47
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Example (Eccesses Specifiers)
class Point:
def __init__( self, x=0, y=0):
self . _x = x
self . _y = y
self . __z = 0
def _display(self)
print ( self._x , self._y , self.__z )
p = Point()
p._x = 3 # p.x NOT same as p._x
p.display()
p.z = 5 # it did not give me error
EC252-Fall2019 ( Chapter 9 ) 45952712 45952712
Dr. Youssef Omran Gdura 45952832 48
Point destroyed
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Example (Accesses Specifiers / Inheratance)
class Point2D:
def __init__(self, x=0, y=0):
self._x = x
self._y = y
class Point3D(Point2D):
def __init__(self, x=0, y=0, z=0):
Point2D.__init__(self , x , y)
self.__z = z;
def display(self):
print(self._x, self._y, self.__z)
p = Point3D(1,2,3) 1, 2 , 3
p.display()
EC252-Fall2019 ( Chapter 9 ) Dr. Youssef Omran Gdura 49
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Chapter # 10
• Modules
• Packages
• Simple Python Projects
• File Handing (spreadsheet files)
• Graphic Projects
• Web sites ( Design & Extracting data
from Web pages)
EC252-Fall2019 ( Chapter 10) Dr. Youssef Omran Gdura 50
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Modules
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your
application.
Use Module to organize our application instead of putting our
code in one file
The first time a module is loaded into a running Python script, it
will not be loaded again even If your code imports the same
module again
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 51
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Packages
A package is a collection of Python modules, i.e., a package is a directory
of Python modules containing an additional __init__.py file.
A package in Python is a directory which MUST contain a special file
called __init__.py. This file can be empty.
The __init__.py distinguishes a package from a regular directories.
A package, which contains module or even sub-packages, can be imported
the same way a module can be imported.
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 52
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Important Modules
Modules
Search on the internet |Python 3 Module index, and we will see the following list of modules
..\Python\Python Module Index — Python 3.8.1 documentation.html
Packages: See
..\Python\Anaconda Python_R Distribution - Free Download.html
Important Modules & Packages
Sys Hand system commands (dir)
Visual 3D graphic
Numpy Numerical Library
SciPy Scientific Library
Email Package supporting the parsing, manipulating, and
generating email messages
Matplotlib ( Chapter 10 )
EC252-Fall2019 Dr. Youssef Omran Gdura 53
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Example Using Module& Package
from visual import * def find_max(numbers):
class Point2D: mx=numbers[0]
def __init__(self, x=0, y=0): for x in numbers:
if x > mx:
self._x = x
mx=x
self._y = y print(mx)
return mx
class Point3D(Point2D):
def __init__(self, x=0, y=0, z=0): from pp import *
Point2D.__init__(self,x,y) from MyPackage.maximum import *
self.__z = z
p = Point3D(1,2,3)
def display(self): p.display()
print(self._x, self._y, self.__z) Foo()
list=[31, 25, 111, 20, 14]
def Foo(): m=find_max(list)
print (m)
print("this is my pp module")
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 54
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
File Handling
So far, we have seen lose their data at the end of their execution, BUT most
applications require saving data to be available whenever it is needed.
A C++ program, for example, could be stored in a file named Myprog.cpp, or an
Excel data can be stored in MyData.xlsx
Python’s standard library has a file class that makes it easy for programmers to make
objects that can store data to, and retrieve data from, disk.
The TextIOWrapper is the Python class that can be used to can store data to, and
retrieve data from, disk, and it is defined in the io module.
Since file processing is such a common activity and it will be imported automatically,
and no import statement is required.
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 55
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python File Methods
open
A function that returns a file object (instance of io.TextIOWrapper).
read
A method that reads the contents of a text file into a single string.
write
A method that writes a string to a text file.
close
A method that closes the file from further processing. When writing to a file, the
close method ensures that all data sent to the file is saved to the file.
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 56
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Methods on Files
The statement
F = open('myfile.txt', 'r')
- Open the file called “myfile.txt”) for reading and returns a file object named “F”
- The first argument to open is the file, and the second argument is a mode.
- The open function supports the following MODES:
- 'r' opens an existing file for reading
- 'w' opens the file for writing
- If file not exist , it will creates a new file
- If the file exist, it will write the new data over the existing data. This
previous data in the file will be lost
- 'a' opens the file to append data to it
- The default MODE is “r” // F = open('myfile.txt')
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 57
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Methods on Files
• The method “write” can be used to save data in a given file object
• For example
F = open('myfile.txt', ‘w') // open file to write data
F . write(‘This Course is\n ') // write the given strings
F . write(‘Object – Oriented\n ') // Notes “\n” new line , it is
F . write(‘Programming\n') // useful when reading each line
• We must close the file using close() method after we finish writing to a file in order
to commit the saving process
• In other words, The saving to the file will be done only after you close the file
F . close()
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 58
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Python Methods on Files
• We can read the contents of the entire file into a single string using the file
object’s read method:
Data = F . read()
• We can also read one line at a time from a text file
for line in F:
print(line . strip()) // reads one line and print it
• The variable “line” is a string, and the strip method removes the trailing newline
('\n') character.
EC252-Fall2019 ( Chapter 10 ) Dr. Youssef Omran Gdura 59