SlideShare une entreprise Scribd logo
1  sur  54
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances

Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic OperationsWai Nwe Tun
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar Hai
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리용 최
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentationNimrita Koul
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
AutoIt for the rest of us - handout
AutoIt for the rest of us - handoutAutoIt for the rest of us - handout
AutoIt for the rest of us - handoutBecky Yoose
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basicsLuigi De Russis
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHPWim Godden
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...Matt Harrison
 

Tendances (20)

Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Trafaret: monads and python
Trafaret: monads and pythonTrafaret: monads and python
Trafaret: monads and python
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
AutoIt for the rest of us - handout
AutoIt for the rest of us - handoutAutoIt for the rest of us - handout
AutoIt for the rest of us - handout
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Python
PythonPython
Python
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 

Similaire à Python Part 2

Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101Nando Vieira
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: FunctionsMarc Gouw
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8pedroburonv
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 

Similaire à Python Part 2 (20)

Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 

Dernier

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 

Dernier (20)

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 

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 djangoteamiti@gmail.com 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 djangoteamiti@gmail.com 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 = ‘mohamedramadan@ibm.com’ 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!