SlideShare a Scribd company logo
PYN101 – Quick Introduction to Coding Using
Python
www.ocdatabases.com
slides.1@ocdatabases.com
949-489-1472
Quick Introduction to coding using Python
• If you have not done so already please fill out your student
questionnaire online as shown or submit them to your
instructor
• Enjoy programming in Python!
PYN101 Quick Introduction to Coding using
Python
• Introduction (s)
• Facilities
• Course Packet (May vary by course and class)
– Student Questionnaire
– Collaterals (Maps, Catalog, Etc.)
– PowerPoint slide deck
– Evaluation form
– Training certificate
4
Quick Introduction to Coding Using Python
I. Introduction to Programming
II. Creating Simple Programs
III. Creating Programs Using Functions
IV. Implementing the Object-Oriented Methodology
V. Handling Programming Errors
I. Introduction to Programming
 History
 Programming Environments
 Overview of Programming
 Introduction to the Software Development Life Cycle
Copyright © 2011 Element K Content LLC. All rights reserved.
History of Python
Programming Environments
Program
salary1=1000
salary2=2000
sum=salary1 + salary2
print("The sum of two salaries is: {}".format(sum))
isSal2Larger = salary1 > salary2
print("Salary2 is larger than salary 1: {}".format(isSal2Larger))
serviceYears1 = 10
serviceYears2 = 5
isYears2Longer = serviceYears2 > serviceYears1
print("Salary2 is larger than salary 1 because their years of
service is longer: {} ". 
format(isSal2Larger and isYears2Longer))
Program Interpreter Results
Program written in
scripting language
Program written in
scripting language
Program displays
results
Program displays
results
Instructions
(statements) written
in Python
Instructions
(statements) written
in Python
Syntax
Keyword used to
create a class
Keyword used to
create a class
Punctuation used to create a
Statement block
Punctuation used to create a
Statement blockclass EmployeeDetails:
#class methods
#initialize instance variables
def init (self, num, name, sal):
self.empNo = num
self.empName = name
self.salary = float(sal)
def computeAllow(self):
return self.salary * 0.05
def computeNetSal(self):
return self.salary - self.computeAllow()
def getName(self):
return self.empName
Statements indented
inside block
Statements indented
inside block
The Programming Life Cycle
Coding
Executing
Debugging
Program containing
an error
Program containing
an error
Instructions written in
a scripting language
Instructions written in
a scripting language
Internal BytecodeInternal BytecodeSource codeSource code
The Python Platform Process
Edit
Verify
Load
Interpret
Phases in the Python
platform process
Phases in the Python
platform process
The Software Development Life Cycle
Maintenance
Testing
Analysis
Software Development
Life Cycle
Implementation Development
Design
Reflective Questions
1. Which programming methodologies do you suggest for your
organization?
2. Will you follow the SDLC approach to developing software in your
company? Why?
II. Creating Simple Programs
 Work with Variables
 Work with Operators
 Control Program Execution
 Work with Lists
Variables
salary = 1750
if salary > 2500:
print ("Salary is greater than 2500")
else:
print ("Salary is less than 2500")
Variable NameVariable Name
Value stored
in the variable
Value stored
in the variable
Operators
salary1=1000
salary2=2000
sum=salary1 + salary2
print ("The sum of the two salaries is %6.2f" % sum)
Expression used to
calculate the sum of
salaries. The result
always on the left.
Expression used to
calculate the sum of
salaries. The result
always on the left.
OperandOperand
Data used in the
expression
Data used in the
expression
The addition operatorThe addition operator
The if Statement
salary = 1750
if salary > 2500:
print("nSalary is greater than 2500")
salary = salary + (0.03 * salary)
Keyword used to
create an if
conditional statement
Keyword used to
create an if
conditional statement
Action StatementAction Statement
Test conditionTest condition
The if...else Statement
salary = 1750
if salary > 2500:
print("nSalary is greater than 2500")
salary = salary + (0.03 * salary)
else:
print("nSalary is less than 2500")
salary = salary + (0.05 * salary)
print("Adjusted salary: {}".format(salary))
Test conditionTest condition
Keyword used to
create if block
Keyword used to
create if block
Keyword used to
create else block
Keyword used to
create else block
Statements to execute
when the test
condition returns true
Statements to execute
when the test
condition returns true
Statements to execute
when the test
condition returns false
Statements to execute
when the test
condition returns false
The elif Statement
if day == 1:
print ("Monday")
elif day == 2:
print ("Tuesday")
elif day == 3:
print ("Wednesday")
elif day == 4:
print ("Thursday")
elif day == 5:
print ("Friday")
elif day == 6:
print ("Saturday")
elif day == 7:
print ("Sunday")
else:
print ("Invalid day value")
Declared with the
elif keyword
Declared with the
elif keyword
Default statementDefault statement
Repeated elif
statements
Repeated elif
statements
Test conditionTest condition
The while Loop
counter = 10
i = 1
#while loop - tests before entering the loop
#make sure the loop variables are initialized
print ("Basic while loop")
while i <= counter:
print("i = {}".format(i))
i = i + 1
Statements to execute
when the test condition
returns true
Statements to execute
when the test condition
returns true
Declared with the
while keyword
Declared with the
while keyword
Test conditionTest condition
Note: there is no do …while … in Python
The for Loop
sum = 0
counter = 15
for i in range(1,counter+1):
sum = sum + i;
print("i = {}".format(sum))
Statement(s) executed
while variable within
sequence range
Statement(s) executed
while variable within
sequence range
Iterating variable declarationIterating variable declaration sequence
expression
sequence
expression
Declared with the
for keyword
Declared with the
for keyword
Lists
marks = [85, 60, 78, 73, 84]
1 2 30
6085 78 73 84
4
List elementsList elements
List initializationList initialization
List nameList name
List IndexList Index
Graphical representation
of list
Graphical representation
of list
Multidimensional Lists
salary2 =[[12000, 13000,14000], [10000,15000,2000]]
tmpsalary = salary2[1][2]
LIst IndexLIst Index
1300012000 14000
1500010000 20000
0100 02
1110 12
Value stored in
the list element
Value stored in
the list element
Graphical representation
of a two-dimensional list
Graphical representation
of a two-dimensional list
List elementsList elements
LIst nameLIst name
Other data structures
• Tuples
t=(12,15,90)
• Dictionaries
d={“name”:”dan”, “phone”:123-456-7890”}
• Sets
• And more
• We will cover these in our more formal programming classes
• There are also modules for manipulating datasets and big data
Reflective Questions
1. What factors do you consider when you declare a variable?
2. How do arrays help you in your job role?
III. Creating Programs Using Functions
 Create Functions
 Work with Built-in Functions
Functions
def calcNetSalary(allowance, sal):
deduction = allowance/100 * sal
print ("The deduction is ${:,.2f}".format(deduction))
netSal = sal - deduction
return netSal
Method bodyMethod body
DeclarationDeclaration
Method nameMethod name ParametersParameters
Function Calls
def print_salary():
#initialize variables
salary = 12000.0
print("The current salary is ${:,.2f}".format(salary))
#calculate net salary by calling a function
netSalary = calcNetSalary(5, salary)
print("The net salary is ${:,.2f}".format(netSalary))
#function to calculate the net salary
def calcNetSalary(allowance, sal):
deduction = allowance/100 * sal
print ("The deduction is ${:,.2f}".format(deduction))
netSal = sal - deduction
return netSal
Function callFunction call
Function
declaration
Function
declaration
Importing modules
import os
print (os.getcwd())
print (os.listdir('.'))
Import declarationImport declaration
Function callsFunction calls
The Python ecosystem includes a huge library of functions across
many domains. This is one of Python’s strong points and is a major
reason for its popularity.
Reflective Questions
1. In what ways does importing modules help you in your job role?
Discuss.
2. Why would you prefer built-in functions rather than defining your
own functions? Discuss.
IV. Implementing the Object-Oriented
Methodology
 Create a Class
 Create an Object
 Create a Constructor
 Create a Subclass
Classes
class EmployeeDetails:
#class methods
#initialize instance variables
def init (self, num, name, sal):
self.empNo = num
self.empName = name
self.salary = float(sal)
def computeAllow(self):
return self.salary * 0.05
def computeNetSal(self):
return self.salary - self.computeAllow()
def getName(self):
return self.empName
Methods in
the class
Methods in
the class
Class name preceded by
the class keyword
Class name preceded by
the class keyword
Instance
variables
Instance
variables
Objects
import employeedetails as ed
#create employee object
empObj = ed.EmployeeDetails()
#get id and name
id=int(input("Please enter employee id: "))
name=input("Please enter employee name: ")
sal=input("PLease enter salary: ")
#calc net salary
empObj.init(id,name,sal)
netSal=empObj.computeNetSal()
print ("Employee details...")
print ("%s with id %d has a salary of $%6.2f"
% (name, id, netSal))
Object nameObject name
Data stored
in object
empObj
Data stored
in object
empObj
Object used to store
employee data
Object used to store
employee data
data for
employee
data for
employee
Class nameClass name
The self Keyword
class EmployeeDetails:
#class methods
#initialize instance variables
def init (self, num, name, sal):
self.empNo = num
self.empName = name
self.salary = float(sal)
def computeAllow(self):
return self.salary * 0.05
def computeNetSal(self):
return self.salary - self.computeAllow()
def getName(self):
return self.empName
Class nameClass name
The self keyword
used to access
instance variables
from within a method
The self keyword
used to access
instance variables
from within a method
Constructors
class EmployeeDetails2:
#class methods
#constructor (initializer) with defaults
def __init__(self, num=0, name='Unknown', sal=0.0):
self.empNo = num
self.empName = name
self.salary = float(sal)
def computeAllow(self):
return self.salary * 0.05
def computeNetSal(self):
return self.salary - self.computeAllow()
def getName(self):
return self.empName
Class nameClass name
Code to initialize the
class
Code to initialize the
class
Constructor parametersConstructor parameters
ConstructorConstructor
Objects using constructor
import employeedetails2 as ed
#get id and name
id=int(input("Please enter employee id: "))
name=input("Please enter employee name: ")
sal=input("Please enter salary: ")
#create employee object using constructor
empObj = ed.EmployeeDetails2(id,name,sal)
#calc net salary
netSal=empObj.computeNetSal()
print ("Employee details...")
print ("%s with id %d has a salary of $%6.2f"
% (name, id, netSal))
Data stored
in object
empObj
Data stored
in object
empObj
Object nameObject name
Class nameClass name
Object nameObject name
Subclasses
from employeedetails2 import EmployeeDetails2
class ProjectMgr(EmployeeDetails2):
#class methods
#constructor (calls superclass) with defaults
def __init__(self, num=0, name='Unknown',
sal=0.0, sub=0):
super().__init__(num, name, sal)
self.numSubordinates = sub
#override calculate net salary
#replace allowance with bonus
def computeNetSal(self):
return self.salary + self.salary * 0.10
#new method to get nbr of subordinates
def getSubordinates(self):
return self.numSubordinates
Keyword used to
call superclass
Keyword used to
call superclass
SubclassSubclass Parent
(super) class
Parent
(super) class
Default values for
constructor
Default values for
constructor
overidden methodoveridden method
New method
extends
functionality
New method
extends
functionality
Instantiate subclass
import projectmgr as pm
#get id and name
id=int(input("Please enter employee id: "))
if id != 0:
name=input("Please enter employee name: ")
sal=input("Please enter salary: ")
subs=int(input("Please enter # subordinates: "))
#create employee object
pmObj = pm.ProjectMgr(id, name, sal, subs)
else:
pmObj = pm.ProjectMgr()
#calc net salary
print ("Employee details...")
print ("%s with id %d has a salary of $%6.2f"
% (pmObj.getName(), id, pmObj.computeNetSal()))
print ("%s with id %d has a %d subordinates"
% (pmObj.getName(), id, pmObj.getSubordinates()))
Create pm object
with arguments
Create pm object
with arguments
Get values for
constructor
Get values for
constructor
Crate default pm
object
Crate default pm
object
Call methods,;
note getName is in
Call methods,;
note getName is in
Reflective Questions
1. Discuss the advantages of using objects in your program.
2. In what ways does method overloading and overriding help you as
you create software in your job role?
Quick introduction to coding using Python
• Please fill out your evaluations online as shown or submit
them to your instructor
• Enjoy programming in Python!

More Related Content

PPTX
DSA 103 Object Oriented Programming :: Week 5
PPTX
Java 102
PPTX
DSA 103 Object Oriented Programming :: Week 4
PPTX
Python basics
PDF
AOP in Python API design
PDF
Friendly Functional Programming
PDF
DSA 103 Object Oriented Programming :: Week 3
PPTX
New Features in JDK 8
DSA 103 Object Oriented Programming :: Week 5
Java 102
DSA 103 Object Oriented Programming :: Week 4
Python basics
AOP in Python API design
Friendly Functional Programming
DSA 103 Object Oriented Programming :: Week 3
New Features in JDK 8

Similar to Introduction to coding using Python (20)

ODP
Introduction to programming with python
PPTX
Introduction to Python External Course !!!
PPTX
Introduction to Python , Overview
PPTX
pythontraining-201jn026043638.pptx
PPTX
Python training
PDF
Introduction To Programming with Python
PPTX
PPt Revision of the basics of python1.pptx
PPTX
funadamentals of python programming language (right from scratch)
PPTX
PDF
Python-Cheat-Sheet.pdf
PPT
Python Training v2
PPTX
Unit 8.4Testing condition _ Developing Games.pptx
PDF
Python: An introduction A summer workshop
PDF
Python Programming A Modular Approach Taneja Sheetal Kumar Naveen
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
PPTX
Introduction to Python Programming
PDF
Quick python reference
PDF
business analytic meeting 1 tunghai university.pdf
PPT
Python-review1.ppt
PPTX
Python programming
Introduction to programming with python
Introduction to Python External Course !!!
Introduction to Python , Overview
pythontraining-201jn026043638.pptx
Python training
Introduction To Programming with Python
PPt Revision of the basics of python1.pptx
funadamentals of python programming language (right from scratch)
Python-Cheat-Sheet.pdf
Python Training v2
Unit 8.4Testing condition _ Developing Games.pptx
Python: An introduction A summer workshop
Python Programming A Modular Approach Taneja Sheetal Kumar Naveen
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python Programming
Quick python reference
business analytic meeting 1 tunghai university.pdf
Python-review1.ppt
Python programming
Ad

More from Dan D'Urso (20)

PPT
SQL201S Accelerated Introduction to MySQL Queries
PPT
LCD201d Database Diagramming with Lucidchart
PPTX
Database Normalization
PPT
VIS201d Visio Database Diagramming
PPT
PRJ101a Project 2013 Accelerated
PPT
PRJ101xl Project Libre Basic Training
PPTX
Stem conference
PDF
SQL200A Microsoft Access SQL Design
PPTX
Microsoft access self joins
PDF
SQL302 Intermediate SQL
PDF
AIN106 Access Reporting and Analysis
PPT
SQL302 Intermediate SQL Workshop 3
PPT
SQL302 Intermediate SQL Workshop 2
PDF
Course Catalog
PPT
SQL302 Intermediate SQL Workshop 1
PDF
SQL212 Oracle SQL Manual
PDF
SQL201W MySQL SQL Manual
PDF
AIN100
PPT
SQL206 SQL Median
PPT
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL201S Accelerated Introduction to MySQL Queries
LCD201d Database Diagramming with Lucidchart
Database Normalization
VIS201d Visio Database Diagramming
PRJ101a Project 2013 Accelerated
PRJ101xl Project Libre Basic Training
Stem conference
SQL200A Microsoft Access SQL Design
Microsoft access self joins
SQL302 Intermediate SQL
AIN106 Access Reporting and Analysis
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 2
Course Catalog
SQL302 Intermediate SQL Workshop 1
SQL212 Oracle SQL Manual
SQL201W MySQL SQL Manual
AIN100
SQL206 SQL Median
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Ad

Recently uploaded (20)

PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Machine Learning_overview_presentation.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Cloud computing and distributed systems.
PDF
Machine learning based COVID-19 study performance prediction
PPT
Teaching material agriculture food technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
MYSQL Presentation for SQL database connectivity
A comparative analysis of optical character recognition models for extracting...
Reach Out and Touch Someone: Haptics and Empathic Computing
Unlocking AI with Model Context Protocol (MCP)
Machine Learning_overview_presentation.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Cloud computing and distributed systems.
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
Encapsulation_ Review paper, used for researhc scholars
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
MYSQL Presentation for SQL database connectivity

Introduction to coding using Python

  • 1. PYN101 – Quick Introduction to Coding Using Python www.ocdatabases.com slides.1@ocdatabases.com 949-489-1472
  • 2. Quick Introduction to coding using Python • If you have not done so already please fill out your student questionnaire online as shown or submit them to your instructor • Enjoy programming in Python!
  • 3. PYN101 Quick Introduction to Coding using Python • Introduction (s) • Facilities • Course Packet (May vary by course and class) – Student Questionnaire – Collaterals (Maps, Catalog, Etc.) – PowerPoint slide deck – Evaluation form – Training certificate
  • 4. 4
  • 5. Quick Introduction to Coding Using Python I. Introduction to Programming II. Creating Simple Programs III. Creating Programs Using Functions IV. Implementing the Object-Oriented Methodology V. Handling Programming Errors
  • 6. I. Introduction to Programming  History  Programming Environments  Overview of Programming  Introduction to the Software Development Life Cycle
  • 7. Copyright © 2011 Element K Content LLC. All rights reserved. History of Python
  • 9. Program salary1=1000 salary2=2000 sum=salary1 + salary2 print("The sum of two salaries is: {}".format(sum)) isSal2Larger = salary1 > salary2 print("Salary2 is larger than salary 1: {}".format(isSal2Larger)) serviceYears1 = 10 serviceYears2 = 5 isYears2Longer = serviceYears2 > serviceYears1 print("Salary2 is larger than salary 1 because their years of service is longer: {} ". format(isSal2Larger and isYears2Longer)) Program Interpreter Results Program written in scripting language Program written in scripting language Program displays results Program displays results Instructions (statements) written in Python Instructions (statements) written in Python
  • 10. Syntax Keyword used to create a class Keyword used to create a class Punctuation used to create a Statement block Punctuation used to create a Statement blockclass EmployeeDetails: #class methods #initialize instance variables def init (self, num, name, sal): self.empNo = num self.empName = name self.salary = float(sal) def computeAllow(self): return self.salary * 0.05 def computeNetSal(self): return self.salary - self.computeAllow() def getName(self): return self.empName Statements indented inside block Statements indented inside block
  • 11. The Programming Life Cycle Coding Executing Debugging Program containing an error Program containing an error Instructions written in a scripting language Instructions written in a scripting language Internal BytecodeInternal BytecodeSource codeSource code
  • 12. The Python Platform Process Edit Verify Load Interpret Phases in the Python platform process Phases in the Python platform process
  • 13. The Software Development Life Cycle Maintenance Testing Analysis Software Development Life Cycle Implementation Development Design
  • 14. Reflective Questions 1. Which programming methodologies do you suggest for your organization? 2. Will you follow the SDLC approach to developing software in your company? Why?
  • 15. II. Creating Simple Programs  Work with Variables  Work with Operators  Control Program Execution  Work with Lists
  • 16. Variables salary = 1750 if salary > 2500: print ("Salary is greater than 2500") else: print ("Salary is less than 2500") Variable NameVariable Name Value stored in the variable Value stored in the variable
  • 17. Operators salary1=1000 salary2=2000 sum=salary1 + salary2 print ("The sum of the two salaries is %6.2f" % sum) Expression used to calculate the sum of salaries. The result always on the left. Expression used to calculate the sum of salaries. The result always on the left. OperandOperand Data used in the expression Data used in the expression The addition operatorThe addition operator
  • 18. The if Statement salary = 1750 if salary > 2500: print("nSalary is greater than 2500") salary = salary + (0.03 * salary) Keyword used to create an if conditional statement Keyword used to create an if conditional statement Action StatementAction Statement Test conditionTest condition
  • 19. The if...else Statement salary = 1750 if salary > 2500: print("nSalary is greater than 2500") salary = salary + (0.03 * salary) else: print("nSalary is less than 2500") salary = salary + (0.05 * salary) print("Adjusted salary: {}".format(salary)) Test conditionTest condition Keyword used to create if block Keyword used to create if block Keyword used to create else block Keyword used to create else block Statements to execute when the test condition returns true Statements to execute when the test condition returns true Statements to execute when the test condition returns false Statements to execute when the test condition returns false
  • 20. The elif Statement if day == 1: print ("Monday") elif day == 2: print ("Tuesday") elif day == 3: print ("Wednesday") elif day == 4: print ("Thursday") elif day == 5: print ("Friday") elif day == 6: print ("Saturday") elif day == 7: print ("Sunday") else: print ("Invalid day value") Declared with the elif keyword Declared with the elif keyword Default statementDefault statement Repeated elif statements Repeated elif statements Test conditionTest condition
  • 21. The while Loop counter = 10 i = 1 #while loop - tests before entering the loop #make sure the loop variables are initialized print ("Basic while loop") while i <= counter: print("i = {}".format(i)) i = i + 1 Statements to execute when the test condition returns true Statements to execute when the test condition returns true Declared with the while keyword Declared with the while keyword Test conditionTest condition Note: there is no do …while … in Python
  • 22. The for Loop sum = 0 counter = 15 for i in range(1,counter+1): sum = sum + i; print("i = {}".format(sum)) Statement(s) executed while variable within sequence range Statement(s) executed while variable within sequence range Iterating variable declarationIterating variable declaration sequence expression sequence expression Declared with the for keyword Declared with the for keyword
  • 23. Lists marks = [85, 60, 78, 73, 84] 1 2 30 6085 78 73 84 4 List elementsList elements List initializationList initialization List nameList name List IndexList Index Graphical representation of list Graphical representation of list
  • 24. Multidimensional Lists salary2 =[[12000, 13000,14000], [10000,15000,2000]] tmpsalary = salary2[1][2] LIst IndexLIst Index 1300012000 14000 1500010000 20000 0100 02 1110 12 Value stored in the list element Value stored in the list element Graphical representation of a two-dimensional list Graphical representation of a two-dimensional list List elementsList elements LIst nameLIst name
  • 25. Other data structures • Tuples t=(12,15,90) • Dictionaries d={“name”:”dan”, “phone”:123-456-7890”} • Sets • And more • We will cover these in our more formal programming classes • There are also modules for manipulating datasets and big data
  • 26. Reflective Questions 1. What factors do you consider when you declare a variable? 2. How do arrays help you in your job role?
  • 27. III. Creating Programs Using Functions  Create Functions  Work with Built-in Functions
  • 28. Functions def calcNetSalary(allowance, sal): deduction = allowance/100 * sal print ("The deduction is ${:,.2f}".format(deduction)) netSal = sal - deduction return netSal Method bodyMethod body DeclarationDeclaration Method nameMethod name ParametersParameters
  • 29. Function Calls def print_salary(): #initialize variables salary = 12000.0 print("The current salary is ${:,.2f}".format(salary)) #calculate net salary by calling a function netSalary = calcNetSalary(5, salary) print("The net salary is ${:,.2f}".format(netSalary)) #function to calculate the net salary def calcNetSalary(allowance, sal): deduction = allowance/100 * sal print ("The deduction is ${:,.2f}".format(deduction)) netSal = sal - deduction return netSal Function callFunction call Function declaration Function declaration
  • 30. Importing modules import os print (os.getcwd()) print (os.listdir('.')) Import declarationImport declaration Function callsFunction calls The Python ecosystem includes a huge library of functions across many domains. This is one of Python’s strong points and is a major reason for its popularity.
  • 31. Reflective Questions 1. In what ways does importing modules help you in your job role? Discuss. 2. Why would you prefer built-in functions rather than defining your own functions? Discuss.
  • 32. IV. Implementing the Object-Oriented Methodology  Create a Class  Create an Object  Create a Constructor  Create a Subclass
  • 33. Classes class EmployeeDetails: #class methods #initialize instance variables def init (self, num, name, sal): self.empNo = num self.empName = name self.salary = float(sal) def computeAllow(self): return self.salary * 0.05 def computeNetSal(self): return self.salary - self.computeAllow() def getName(self): return self.empName Methods in the class Methods in the class Class name preceded by the class keyword Class name preceded by the class keyword Instance variables Instance variables
  • 34. Objects import employeedetails as ed #create employee object empObj = ed.EmployeeDetails() #get id and name id=int(input("Please enter employee id: ")) name=input("Please enter employee name: ") sal=input("PLease enter salary: ") #calc net salary empObj.init(id,name,sal) netSal=empObj.computeNetSal() print ("Employee details...") print ("%s with id %d has a salary of $%6.2f" % (name, id, netSal)) Object nameObject name Data stored in object empObj Data stored in object empObj Object used to store employee data Object used to store employee data data for employee data for employee Class nameClass name
  • 35. The self Keyword class EmployeeDetails: #class methods #initialize instance variables def init (self, num, name, sal): self.empNo = num self.empName = name self.salary = float(sal) def computeAllow(self): return self.salary * 0.05 def computeNetSal(self): return self.salary - self.computeAllow() def getName(self): return self.empName Class nameClass name The self keyword used to access instance variables from within a method The self keyword used to access instance variables from within a method
  • 36. Constructors class EmployeeDetails2: #class methods #constructor (initializer) with defaults def __init__(self, num=0, name='Unknown', sal=0.0): self.empNo = num self.empName = name self.salary = float(sal) def computeAllow(self): return self.salary * 0.05 def computeNetSal(self): return self.salary - self.computeAllow() def getName(self): return self.empName Class nameClass name Code to initialize the class Code to initialize the class Constructor parametersConstructor parameters ConstructorConstructor
  • 37. Objects using constructor import employeedetails2 as ed #get id and name id=int(input("Please enter employee id: ")) name=input("Please enter employee name: ") sal=input("Please enter salary: ") #create employee object using constructor empObj = ed.EmployeeDetails2(id,name,sal) #calc net salary netSal=empObj.computeNetSal() print ("Employee details...") print ("%s with id %d has a salary of $%6.2f" % (name, id, netSal)) Data stored in object empObj Data stored in object empObj Object nameObject name Class nameClass name Object nameObject name
  • 38. Subclasses from employeedetails2 import EmployeeDetails2 class ProjectMgr(EmployeeDetails2): #class methods #constructor (calls superclass) with defaults def __init__(self, num=0, name='Unknown', sal=0.0, sub=0): super().__init__(num, name, sal) self.numSubordinates = sub #override calculate net salary #replace allowance with bonus def computeNetSal(self): return self.salary + self.salary * 0.10 #new method to get nbr of subordinates def getSubordinates(self): return self.numSubordinates Keyword used to call superclass Keyword used to call superclass SubclassSubclass Parent (super) class Parent (super) class Default values for constructor Default values for constructor overidden methodoveridden method New method extends functionality New method extends functionality
  • 39. Instantiate subclass import projectmgr as pm #get id and name id=int(input("Please enter employee id: ")) if id != 0: name=input("Please enter employee name: ") sal=input("Please enter salary: ") subs=int(input("Please enter # subordinates: ")) #create employee object pmObj = pm.ProjectMgr(id, name, sal, subs) else: pmObj = pm.ProjectMgr() #calc net salary print ("Employee details...") print ("%s with id %d has a salary of $%6.2f" % (pmObj.getName(), id, pmObj.computeNetSal())) print ("%s with id %d has a %d subordinates" % (pmObj.getName(), id, pmObj.getSubordinates())) Create pm object with arguments Create pm object with arguments Get values for constructor Get values for constructor Crate default pm object Crate default pm object Call methods,; note getName is in Call methods,; note getName is in
  • 40. Reflective Questions 1. Discuss the advantages of using objects in your program. 2. In what ways does method overloading and overriding help you as you create software in your job role?
  • 41. Quick introduction to coding using Python • Please fill out your evaluations online as shown or submit them to your instructor • Enjoy programming in Python!

Editor's Notes

  • #5: The red arrow points to the training center. The yellow sunburst is the intersection of the Ortega Highway and Interstate 5, the route by which most students will reach the us.
  • #6: OV #: Source File Name(s): Figure File Name: Comments:
  • #7: OV #: Source File Name(s): Figure File Name: Comments:
  • #15: OV #: Source File Name(s): Figure File Name: Comments:
  • #16: OV #: Source File Name(s): Figure File Name: Comments:
  • #27: OV #: Source File Name(s): Figure File Name: Comments:
  • #28: OV #: Source File Name(s): Figure File Name: Comments:
  • #32: OV #: Source File Name(s): Figure File Name: Comments:
  • #33: OV #: Source File Name(s): Figure File Name: Comments:
  • #41: OV #: Source File Name(s): Figure File Name: Comments: