SlideShare a Scribd company logo
Python Programming
Mohamed Ramadan
Application Developer
Java Certified Associative
Cognitive Computing certified practitioner
Agile – Design Thinking Certified Practitioner
Day 2
AGENDA
Deep into
◈ Exception Handling
◈ Modules, Packages
OOP
◈ Key words
◈ Concepts
Data base
◈ MySQLdb Module
Other
◈ Regular Expression
◈ Clean code
◈ Lab
EXCEPTION HANDLING
ERRORS
ERROR
SYNTAX LOGICAL EXCEPTION
Exception Handling Continue
◈ Error in syntax
eval(“26”
syntaxError: Missing ‘)’
◈ Error during execution are called Exceptions
print firstname
NameError: name ‘firstname’ is not defined
Exception Handling Continue
try:
#operations goes here.
except Exception_type_1:
#if Exception_type_1 happened execute this code.
except Exception_type_2 as e:
#if Exception_type_2 happened print(e)
else:
#if there is no exceptions execute this code.
finally:
#execute this code at any case.
Exception Handling Continue
Example 1
try:
file = open("test.txt",“r")
content = file.read()
except IOError:
print "Error: cannot find file"
else:
print “file content captured successfully"
finally:
file.close()
Exception Handling Continue
Example 2
x = 5
y = 0
try:
z = x / y
except ZeroDivisionError as e:
print e
#output integer division or modulo by zero
Exception Handling Continue
Raising Exceptions
raise ErrorName(“Error Message”)
Example
raise ZeroDivisionError(“You can’t divide by zero”)
Levels
Spaghetti
Procedural
Modular
Object
Oriented+ Functions
+ Modules
Module
Raising Modularity main purposes is reusability enrichment.
Creating python files and importing their functions
From greeting import hi, bye
hi()
bye()
greeting.py
_______________
def hi():
print “hi”
def bye():
print “bye”
Package
Putting similar modules into directory containers folders
Package folder must contain a file named __init__.py to tell that this folder
will contain python modules.
We can override __all__ list to specify which properties should be exposed to *
in the API
__all__ = [“hi”, “bye”]
From human.greeting import *
hi()
bye()
greeting.py
_______________
def hi():
print “hi”
def bye():
print “bye”
Object Oriented
Programming
Intro
Tony Stark object
Height = 170 cm
Weight = 70 kg
Smart = True
Speak()
Invent()
Iron suit object
velocity = 1000 km/h
Armed = True
fly()
attack()
Properties
Methods
Wear(Iron Suit object)
OOP
Keywords
class
class Human():
pass
Human Class
A Class is a template definition of an object’s properties and methods.
Object
class Human():
pass
man = Human()
women = Human()
Human Class
An Object is an instance of a class.
women object man object
Constructor
class Human():
def __init__(self):
print “Hey!”
man = Human()
Output
Hey!
Human Class
A Constructor is a method called at the moment an object instantiated.
man object
Hey!
__init__()
Instance Variables
class Human():
def __init__(self, name):
self.name = name
man = Human(“Mohamed”)
Human Class
An Object characteristic, such as the name, weight, ...
man object
__init__()
name
Mohamed
Class Variables
class Human():
working = True
def __init__(self, name):
self.name = name
man = Human(“Mohamed”)
women = Human(“Mona”)
Human Class
A Class variable is the variable shared by all instances.
He works
__init__()
working
Mohamed
name
She works
Mona
Class Variable
class Employee():
vacation_balance = 0
def __init__(self, name):
self.name = name
e1 = Employee(“Mohamed”)
e2 = Employee(“Ahmed”)
e1.vacation_balance = 1
print “e1: ”, e1.vacation_balance
print “e2: ”, e2.vacation_balance
print “Employee: ”, Employee.vacation_balance
Employee.vacation_balance = 2
print “e1: ”, e1.vacation_balance
print “e2: ”, e2.vacation_balance
print “Employee: ”, Employee.vacation_balance
Output
E1: 1
E2: 0
Employee: 0
E1: 1
E2: 2
Employee: 2
Instance Method
class Human():
def __init__(self, name):
self.name = name
def speak(self):
print “My name is”, self.name
# Object passed implicitly to instance method self
man = Human(“Mohamed”)
man.speak()
Human Class
An Instance method is an object capability like walk, talk, ..
man object
__init__()
Speak()
name
My name is Mohamed
Class Method
class Human():
fault = 0
def __init__(self, name):
self.name = name
@classmethod
def makesfault(clas):
clas.fault += 1
print clas.fault
Human.makesfault() #1
Man = Human(“Ali”)
Man2 = Human(“Ahmed”)
Man.makesfault() #2
Man2.makesfault() #3
Human Class
A Class method is that method shared by all instances.
__init__()
fault
name
makesfault()
Static Method
class Human():
def __init__(self, name):
self.name = name
@staticmethod
def tempmeasure(temp):
if temp == 37:
print “Normal”
print “Not Normal”
Human.tempmeasure(38) # Normal
Human Class
It is a normal function has logic related to the class.
__init__()
name
tempmeasure()
Class Method VS Static Method
# Cls (class) is implicitly passed to
class method as well as self(object) in
instance method.
# Class method is related to the class
it self we don’t call class method
using instances.
class Human:
@classmethod
def walk(cls):
print “walking”
Human.walk()
# A normal function has logic related
to the class.
# Doesn’t have any implicitly passed
arguments.
# Can be called by both class and
instance.
# We call it helper methods.
class Human:
@staticmethod
def walk():
print “walking”
Human.walk()
OOP
Concepts
Inheritance
HUMAN
Employee
Teacher Engineer
#inheritance
Super is used to call the parent class without knowing its name.
#inheritance
#super
class SubClass(ParentClass):
def __init__(self):
ParentClass.__init__(self)
class SubClass(ParentClass):
def __init__(self):
super(SubClass, self).__init__()
class Human():
def __init__(self, name):
self.name = name
def speak(self):
print “My name is ” + self.name
class Employee(Human):
def __init__(self, name, salary)
super(Employee, self).__init__(name)
self.salary = salary
def work(self):
print “I’m working now”
emp = Employee(“Ahmed”, 1000)
emp.speake()
emp.work()
Human
Employee
#inheritance
Report
Python Supports Multiple Inheritance
1. How super function handle multiple inheritance.
2. If Human and Mammal have same method eat but with different implementation,
when child Employee calls eat method how python handle this case.
Prove your opinion with example.
Mail report to djangoteamiti@gmail.com
Subject: “Report #2 – Name – sheet number”
# Multiple inheritance
Human Mammal
Employee
Polymorphism
Poly means “Many” morphism means “Forms”. Different classes might define the same
method or property.
#polymorphism
#intro
Bird Class
Fly()
Eagle Fly()
Dove Fly()
Penguin Fly()
I fly very fast
I fly for long distances
I can’t fly 
I fly ☺
class Human():
def __init__(self, name):
self.name = name
def speak(self):
print “My name is ” + self.name
class Employee(Human):
def __init__(self, name, salary)
super(Employee, self).__init__(name)
self.salary = salary
def speak(self):
print “My salary is ” , self.salary
emp = Employee(“Ahmed”, 1000)
emp.speake()
Human
Employee
# Method overriding
>> My salary is 500
Report
Can we do overloading in python ?
1. If Yes, Tell me how
2. If No, Tell me why
Support your Answer by example.
Mail report to djangoteamiti@gmail.com
Subject: “Report #3 – Name – sheet number”
# Method overloading
Encapsulation
Encapsulation is packing data and functions into one component “a class for example”
and then controlling access to that component.
#encapsulation
#intro
Class
“Mohamed”
getName()
Private variable can be defined by setting double __ before its name
Then it is only visible inside the class
class Human():
def __init__(self, name, age):
self.__name = name #private __name
self.age = age
def getName(self):
return “My name is ” + self.__name
emp = Employee(“Ahmed”, 30)
print emp.age
print emp.__name
print emp.getName()
#encapsulation
>> 30
>> AttributeError: ‘Human’ object has no attribute ‘__name’
Break
You can go as far as you push.
00:15:00 minutes
DATABASE
MySQLdb
First of all we need MySQLdb module that enabling issuing and executing sql.
Steps:
• Import MySQLdb module.
• Acquire connection to the database.
• Create cursor (SQL executor).
• Execute sql
- Commit for insert and delete
- fetch for select
- rollback for exception
• Close connection.
#intro
On python shell
>> import MySQLdb
>>
# No news is a good news
Else, install the module
>> sudo apt-get install python-mysqldb
#Database
# Get Connection
import MySQLdb
db = MySQLdb.connect(“Host”, “user”, “password”, “db name”)
# Get Cursor executor
cursor = db.cursor()
# Execute sql using cursor
Cursor.execute(sql string)
#Database
READ Operation on any database means to fetch some useful information from the
database.
fetchone() It fetches the next row of a query result set. A result set is an object
that is returned when a cursor object is used to query a table.
fetchall() It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result set.
Rowcount This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
#Database
First create a new database called “mytestdb” in MySQL
for testing
import MySQLdb
db = MySQLdb.connect("localhost","root","admin","mytestdb")
cursor =db.cursor()
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data =cursor.fetchone()
print"Database version : %s “ % data
db.close()
#Database
#fetchone()
import MySQLdb
db = MySQLdb.connect("localhost","root","admin","mytestdb")
cursor =db.cursor()
sql_str1= “select * from employee”
try:
cursor.execute(sql_str1)
results = cursor.fetchall()
for result in results:
print result[0] #id
print result[1] #name
except:
db.rollback()
db.close()
#Database
#fetchall()
import MySQLdb
db = MySQLdb.connect("localhost","root","admin","mytestdb")
cursor =db.cursor()
sql_str1= “insert into employee values (1, ‘Ahmed’)”
try:
cursor.execute(sql_str1)
db.commit()
except:
db.rollback()
finally:
db.close()
#Database
#commit()
Regular Expression
Python module re has many functions
Match() # check for entire matching
Search() # checks for any matching
import re
ptrn = r’^[a-zA-z0-9]+@[a-z]+.[a-z]{2,4}$’
email = ‘mohamedramadan@ibm.com’
Result = re.match(ptrn, email)
If result:
print “Welcome”, result.group()
else:
print “Invalid email”
LAB TIME
Setup the following classes
Person:
- attributes (full_name, money, sleepmood,healthRate)
- methods (sleep, eat, buy)
Employee(is a Person class):
- attributes (id, email, workmood, salary, is_manager)
- methods (work, sendEmail)
Office:
- attributes (name, employees)
- methods (get_all_employees, get_employee, fire, hire)
Implement Employee methods
sleep(hours): Method in Person class( 7 happy, <7 tired, >7  lazy)
eat(meals): Method in Person class( 3 meals  100 health rate, 2 meals
75 health rate , 1 meal  50 health rate)
buy(items): Method in Person class( 1 Item decrees Money 10 LE)
sendEmail(to, suject, body receiver_name): on call it creates a
file represent the email.
Implement Employee methods cont…
work(hours): Method in Employee class( 8 happy, > 8
tired, > 8  lazy)
Salary: Property must be 1000 or more
Health rate: Property must be between 0 and 100
Email: Property must be verified
Implement Office methods
get_all_employees(): Method in Office class get all current employees
get_employee(empId): Method in Office class get employee data of given
employee id, and if a manager display all info except salary.
hire(Employee): Method in Office class hires the given employee
fire(empId): Method in Office class fires the given employeeid
DB table Employee should maintain employee objects and office retrievals
Let the program be user command interface.
Print a menu with the functionalities allowed. For example
For adding new employee enter “add”
If manager press “m” if normal employee press “3”
Enter your data:
>> Name:
>> age:
The final menu option is “q” to quit the application.
Mohamed Ramadan
That’s all for day 2
Thank you!

More Related Content

PDF
Python Part 1
PDF
Active Support Core Extensions (1)
PDF
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
PDF
Python introduction
PDF
Python for text processing
ODP
An Intro to Python in 30 minutes
PDF
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
PDF
Python in 90 minutes
Python Part 1
Active Support Core Extensions (1)
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Python introduction
Python for text processing
An Intro to Python in 30 minutes
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Python in 90 minutes

What's hot (20)

PDF
Python Tutorial
PDF
Begin with Python
PDF
Matlab and Python: Basic Operations
PDF
Advanced Python, Part 2
PDF
Learn 90% of Python in 90 Minutes
PPTX
Python 표준 라이브러리
PPTX
Python Traning presentation
PPTX
Learn python in 20 minutes
PDF
Intro to Python
PDF
Trafaret: monads and python
PPTX
Python Workshop - Learn Python the Hard Way
PDF
AutoIt for the rest of us - handout
PPTX
Learn python - for beginners - part-2
PDF
Python programming : Inheritance and polymorphism
PDF
AmI 2016 - Python basics
ODP
The promise of asynchronous PHP
PDF
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
PPTX
ODP
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Python Tutorial
Begin with Python
Matlab and Python: Basic Operations
Advanced Python, Part 2
Learn 90% of Python in 90 Minutes
Python 표준 라이브러리
Python Traning presentation
Learn python in 20 minutes
Intro to Python
Trafaret: monads and python
Python Workshop - Learn Python the Hard Way
AutoIt for the rest of us - handout
Learn python - for beginners - part-2
Python programming : Inheritance and polymorphism
AmI 2016 - Python basics
The promise of asynchronous PHP
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Ad

Similar to Python Part 2 (20)

PDF
Object Orientation vs Functional Programming in Python
PDF
Metaprogramming 101
PDF
Python magicmethods
PDF
Practical Celery
KEY
Desarrollando aplicaciones web en minutos
KEY
Intro to Ruby - Twin Cities Code Camp 7
PDF
Python introduction 2
PDF
Class 7a: Functions
PDF
Postobjektové programovanie v Ruby
PPT
Spsl v unit - final
PPT
Spsl vi unit final
KEY
Why ruby
PDF
Magic of Ruby
KEY
Testing My Patience
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PDF
Ruby Intro {spection}
PDF
Ruby tricks2
PPTX
Lo nuevo de Django 1.7 y 1.8
KEY
DjangoCon US 2011 - Monkeying around at New Relic
KEY
Djangocon11: Monkeying around at New Relic
Object Orientation vs Functional Programming in Python
Metaprogramming 101
Python magicmethods
Practical Celery
Desarrollando aplicaciones web en minutos
Intro to Ruby - Twin Cities Code Camp 7
Python introduction 2
Class 7a: Functions
Postobjektové programovanie v Ruby
Spsl v unit - final
Spsl vi unit final
Why ruby
Magic of Ruby
Testing My Patience
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Ruby Intro {spection}
Ruby tricks2
Lo nuevo de Django 1.7 y 1.8
DjangoCon US 2011 - Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
Ad

Recently uploaded (20)

PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Nekopoi APK 2025 free lastest update
PDF
System and Network Administraation Chapter 3
PDF
top salesforce developer skills in 2025.pdf
PPTX
Transform Your Business with a Software ERP System
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
medical staffing services at VALiNTRY
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
assetexplorer- product-overview - presentation
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Adobe Illustrator 28.6 Crack My Vision of Vector Design
CHAPTER 2 - PM Management and IT Context
Computer Software and OS of computer science of grade 11.pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Wondershare Filmora 15 Crack With Activation Key [2025
Nekopoi APK 2025 free lastest update
System and Network Administraation Chapter 3
top salesforce developer skills in 2025.pdf
Transform Your Business with a Software ERP System
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
medical staffing services at VALiNTRY
Odoo POS Development Services by CandidRoot Solutions
iTop VPN Free 5.6.0.5262 Crack latest version 2025
Design an Analysis of Algorithms II-SECS-1021-03
Upgrade and Innovation Strategies for SAP ERP Customers
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
assetexplorer- product-overview - presentation
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025

Python Part 2

  • 1. Python Programming Mohamed Ramadan Application Developer Java Certified Associative Cognitive Computing certified practitioner Agile – Design Thinking Certified Practitioner Day 2
  • 2. AGENDA Deep into ◈ Exception Handling ◈ Modules, Packages OOP ◈ Key words ◈ Concepts Data base ◈ MySQLdb Module Other ◈ Regular Expression ◈ Clean code ◈ Lab
  • 4. Exception Handling Continue ◈ Error in syntax eval(“26” syntaxError: Missing ‘)’ ◈ Error during execution are called Exceptions print firstname NameError: name ‘firstname’ is not defined
  • 5. Exception Handling Continue try: #operations goes here. except Exception_type_1: #if Exception_type_1 happened execute this code. except Exception_type_2 as e: #if Exception_type_2 happened print(e) else: #if there is no exceptions execute this code. finally: #execute this code at any case.
  • 6. Exception Handling Continue Example 1 try: file = open("test.txt",“r") content = file.read() except IOError: print "Error: cannot find file" else: print “file content captured successfully" finally: file.close()
  • 7. Exception Handling Continue Example 2 x = 5 y = 0 try: z = x / y except ZeroDivisionError as e: print e #output integer division or modulo by zero
  • 8. Exception Handling Continue Raising Exceptions raise ErrorName(“Error Message”) Example raise ZeroDivisionError(“You can’t divide by zero”)
  • 10. Module Raising Modularity main purposes is reusability enrichment. Creating python files and importing their functions From greeting import hi, bye hi() bye() greeting.py _______________ def hi(): print “hi” def bye(): print “bye”
  • 11. Package Putting similar modules into directory containers folders Package folder must contain a file named __init__.py to tell that this folder will contain python modules. We can override __all__ list to specify which properties should be exposed to * in the API __all__ = [“hi”, “bye”] From human.greeting import * hi() bye() greeting.py _______________ def hi(): print “hi” def bye(): print “bye”
  • 13. Intro Tony Stark object Height = 170 cm Weight = 70 kg Smart = True Speak() Invent() Iron suit object velocity = 1000 km/h Armed = True fly() attack() Properties Methods Wear(Iron Suit object)
  • 15. class class Human(): pass Human Class A Class is a template definition of an object’s properties and methods.
  • 16. Object class Human(): pass man = Human() women = Human() Human Class An Object is an instance of a class. women object man object
  • 17. Constructor class Human(): def __init__(self): print “Hey!” man = Human() Output Hey! Human Class A Constructor is a method called at the moment an object instantiated. man object Hey! __init__()
  • 18. Instance Variables class Human(): def __init__(self, name): self.name = name man = Human(“Mohamed”) Human Class An Object characteristic, such as the name, weight, ... man object __init__() name Mohamed
  • 19. Class Variables class Human(): working = True def __init__(self, name): self.name = name man = Human(“Mohamed”) women = Human(“Mona”) Human Class A Class variable is the variable shared by all instances. He works __init__() working Mohamed name She works Mona
  • 20. Class Variable class Employee(): vacation_balance = 0 def __init__(self, name): self.name = name e1 = Employee(“Mohamed”) e2 = Employee(“Ahmed”) e1.vacation_balance = 1 print “e1: ”, e1.vacation_balance print “e2: ”, e2.vacation_balance print “Employee: ”, Employee.vacation_balance Employee.vacation_balance = 2 print “e1: ”, e1.vacation_balance print “e2: ”, e2.vacation_balance print “Employee: ”, Employee.vacation_balance Output E1: 1 E2: 0 Employee: 0 E1: 1 E2: 2 Employee: 2
  • 21. Instance Method class Human(): def __init__(self, name): self.name = name def speak(self): print “My name is”, self.name # Object passed implicitly to instance method self man = Human(“Mohamed”) man.speak() Human Class An Instance method is an object capability like walk, talk, .. man object __init__() Speak() name My name is Mohamed
  • 22. Class Method class Human(): fault = 0 def __init__(self, name): self.name = name @classmethod def makesfault(clas): clas.fault += 1 print clas.fault Human.makesfault() #1 Man = Human(“Ali”) Man2 = Human(“Ahmed”) Man.makesfault() #2 Man2.makesfault() #3 Human Class A Class method is that method shared by all instances. __init__() fault name makesfault()
  • 23. Static Method class Human(): def __init__(self, name): self.name = name @staticmethod def tempmeasure(temp): if temp == 37: print “Normal” print “Not Normal” Human.tempmeasure(38) # Normal Human Class It is a normal function has logic related to the class. __init__() name tempmeasure()
  • 24. Class Method VS Static Method # Cls (class) is implicitly passed to class method as well as self(object) in instance method. # Class method is related to the class it self we don’t call class method using instances. class Human: @classmethod def walk(cls): print “walking” Human.walk() # A normal function has logic related to the class. # Doesn’t have any implicitly passed arguments. # Can be called by both class and instance. # We call it helper methods. class Human: @staticmethod def walk(): print “walking” Human.walk()
  • 28. Super is used to call the parent class without knowing its name. #inheritance #super class SubClass(ParentClass): def __init__(self): ParentClass.__init__(self) class SubClass(ParentClass): def __init__(self): super(SubClass, self).__init__()
  • 29. class Human(): def __init__(self, name): self.name = name def speak(self): print “My name is ” + self.name class Employee(Human): def __init__(self, name, salary) super(Employee, self).__init__(name) self.salary = salary def work(self): print “I’m working now” emp = Employee(“Ahmed”, 1000) emp.speake() emp.work() Human Employee #inheritance
  • 30. Report Python Supports Multiple Inheritance 1. How super function handle multiple inheritance. 2. If Human and Mammal have same method eat but with different implementation, when child Employee calls eat method how python handle this case. Prove your opinion with example. Mail report to [email protected] Subject: “Report #2 – Name – sheet number” # Multiple inheritance Human Mammal Employee
  • 32. Poly means “Many” morphism means “Forms”. Different classes might define the same method or property. #polymorphism #intro Bird Class Fly() Eagle Fly() Dove Fly() Penguin Fly() I fly very fast I fly for long distances I can’t fly  I fly ☺
  • 33. class Human(): def __init__(self, name): self.name = name def speak(self): print “My name is ” + self.name class Employee(Human): def __init__(self, name, salary) super(Employee, self).__init__(name) self.salary = salary def speak(self): print “My salary is ” , self.salary emp = Employee(“Ahmed”, 1000) emp.speake() Human Employee # Method overriding >> My salary is 500
  • 34. Report Can we do overloading in python ? 1. If Yes, Tell me how 2. If No, Tell me why Support your Answer by example. Mail report to [email protected] Subject: “Report #3 – Name – sheet number” # Method overloading
  • 36. Encapsulation is packing data and functions into one component “a class for example” and then controlling access to that component. #encapsulation #intro Class “Mohamed” getName() Private variable can be defined by setting double __ before its name Then it is only visible inside the class
  • 37. class Human(): def __init__(self, name, age): self.__name = name #private __name self.age = age def getName(self): return “My name is ” + self.__name emp = Employee(“Ahmed”, 30) print emp.age print emp.__name print emp.getName() #encapsulation >> 30 >> AttributeError: ‘Human’ object has no attribute ‘__name’
  • 38. Break You can go as far as you push. 00:15:00 minutes
  • 40. First of all we need MySQLdb module that enabling issuing and executing sql. Steps: • Import MySQLdb module. • Acquire connection to the database. • Create cursor (SQL executor). • Execute sql - Commit for insert and delete - fetch for select - rollback for exception • Close connection. #intro
  • 41. On python shell >> import MySQLdb >> # No news is a good news Else, install the module >> sudo apt-get install python-mysqldb #Database
  • 42. # Get Connection import MySQLdb db = MySQLdb.connect(“Host”, “user”, “password”, “db name”) # Get Cursor executor cursor = db.cursor() # Execute sql using cursor Cursor.execute(sql string) #Database
  • 43. READ Operation on any database means to fetch some useful information from the database. fetchone() It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table. fetchall() It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves the remaining rows from the result set. Rowcount This is a read-only attribute and returns the number of rows that were affected by an execute() method. #Database
  • 44. First create a new database called “mytestdb” in MySQL for testing import MySQLdb db = MySQLdb.connect("localhost","root","admin","mytestdb") cursor =db.cursor() cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data =cursor.fetchone() print"Database version : %s “ % data db.close() #Database #fetchone()
  • 45. import MySQLdb db = MySQLdb.connect("localhost","root","admin","mytestdb") cursor =db.cursor() sql_str1= “select * from employee” try: cursor.execute(sql_str1) results = cursor.fetchall() for result in results: print result[0] #id print result[1] #name except: db.rollback() db.close() #Database #fetchall()
  • 46. import MySQLdb db = MySQLdb.connect("localhost","root","admin","mytestdb") cursor =db.cursor() sql_str1= “insert into employee values (1, ‘Ahmed’)” try: cursor.execute(sql_str1) db.commit() except: db.rollback() finally: db.close() #Database #commit()
  • 47. Regular Expression Python module re has many functions Match() # check for entire matching Search() # checks for any matching import re ptrn = r’^[a-zA-z0-9]+@[a-z]+.[a-z]{2,4}$’ email = ‘[email protected]’ Result = re.match(ptrn, email) If result: print “Welcome”, result.group() else: print “Invalid email”
  • 49. Setup the following classes Person: - attributes (full_name, money, sleepmood,healthRate) - methods (sleep, eat, buy) Employee(is a Person class): - attributes (id, email, workmood, salary, is_manager) - methods (work, sendEmail) Office: - attributes (name, employees) - methods (get_all_employees, get_employee, fire, hire)
  • 50. Implement Employee methods sleep(hours): Method in Person class( 7 happy, <7 tired, >7  lazy) eat(meals): Method in Person class( 3 meals  100 health rate, 2 meals 75 health rate , 1 meal  50 health rate) buy(items): Method in Person class( 1 Item decrees Money 10 LE) sendEmail(to, suject, body receiver_name): on call it creates a file represent the email.
  • 51. Implement Employee methods cont… work(hours): Method in Employee class( 8 happy, > 8 tired, > 8  lazy) Salary: Property must be 1000 or more Health rate: Property must be between 0 and 100 Email: Property must be verified
  • 52. Implement Office methods get_all_employees(): Method in Office class get all current employees get_employee(empId): Method in Office class get employee data of given employee id, and if a manager display all info except salary. hire(Employee): Method in Office class hires the given employee fire(empId): Method in Office class fires the given employeeid DB table Employee should maintain employee objects and office retrievals
  • 53. Let the program be user command interface. Print a menu with the functionalities allowed. For example For adding new employee enter “add” If manager press “m” if normal employee press “3” Enter your data: >> Name: >> age: The final menu option is “q” to quit the application.
  • 54. Mohamed Ramadan That’s all for day 2 Thank you!