Python PDF
Python PDF
Chapter # 7
Introduction to
Python
Programming Language
Class names start with an uppercase letter. All other identifiers start with
a lowercase letter.
Input Statement
• A hash sign (#) that is not inside a string literal begins a comment
• 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
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
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Function in Python
Functions: The heading (prototype) contains
Keyword def … Function name
Parentheses; and finally a colon.
def function_name(parameters):
Statement1
statement2
...
...
return [expr]
Functions Examples
Example #1 Example #2
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
Pass-by Reference
In Python, arguments are always passed by reference. For
example:
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])
Chapter # 8
Python
• Lists
• Arrays
• Tuples
• Sets
• Dictionaries
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
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
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
EXAMPLE
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"]
• Adding an element
cars.append("Honda")
Arrays in Python
Python does not have built-in support for Arrays, but Python Lists can be
used instead.
• Sort Array
L . sort () =[“a”, “b”,“c”, “x”]
• Reverese array
L . reverse() =[“x”, “c”,“b”, “a”]
index() Returns the index of the first element with the specified value
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
Tuples
3- Range of indexs
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon")
print( thistuple[2:5]) ('cherry', 'orange', 'kiwi')
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)
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'}
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 ([]).
Python Dictionaries
dict = {'name': 'john','code':6734, 5: ‘You'}
Chapter # 9
Classes
Python
Constructor: Only one constructor that defines and initializes data members
def _ _init_ _ ( self , argument list ) :
constructor body
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++
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
2. Class name.
_ _name_ _:
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
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
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
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” )
p = Point()
p._x = 3 # p.x NOT same as p._x
p.display()
p.z = 5 # it did not give me error
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)
Modules
Consider a module to be the same as a code library.
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.
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
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.
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.
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.
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.
• For example
• 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
ﺎﻣﻌ ﺔ
ﻗﺳم ھﻧدﺳﺔ اﻟﺣﺎﺳب- ﻛﻠﯾﺔ اﻟﮭﻧدﺳـﺔ
Data = F . read()
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.