SlideShare a Scribd company logo
Functions
In
Python
Learning Objectives
● Explain how to define and write functions
● Illustrate how to call functions
● Analyze how to pass different arguments to
functions
● Demonstrate how to return a value from
functions
Computer Science Department, UET Lahore.
Working Example
Write a Python Program to calculate the mean of five
numbers input by user.
Formula for calculating the mean is:
For Example:
Computer Science Department, UET Lahore.
Input: 1, 2, 3, 4
Output: 2.5
Mean = {Sum of numbers} ÷ {Total numbers}
Working Example: Solution
Computer Science Department, UET Lahore.
add = 0
for x in range(0,5,1):
num = int(input(“Enter Number: ”))
add = add + num
print(“Mean: ”, add/5)
Output:
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Mean: 3.0
To calculate the mean,
We can use this method
Is there any better Solution?
Computer Science Department, UET Lahore.
add = 0
for x in range(0,5,1):
num = int(input(“Enter Number: ”))
add = add + num
print(“Mean: ”, add/5)
Output:
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Mean: 3.0
To calculate the mean,
We can use this method
Is there any better Solution?
Computer Science Department, UET Lahore.
● Better solution in terms of readability and
simplicity.
● Yes, there is.
● But before moving to the solution lets take a real
life example of Automobile factory.
Automobiles in Factory
● How do the automobiles are created in the
factory?
Computer Science Department, UET Lahore.
Components of Automobiles
● Wheels, Brakes, Engine, Steering Wheels etc are
the components of the car.
Computer Science Department, UET Lahore.
Automobiles in Factory
● Wheels, Brakes, Engine, Steering Wheels are
manufactured separately and they are assembled
in the automobile factory.
Computer Science Department, UET Lahore.
Functions
● Functions are like short programs that can take
input, process on it, and may return the results
● Functions are like building blocks. They let you
divide complicated programs into manageable
pieces
Computer Science Department, UET Lahore.
Functions: How to Create?
● Functions are defined using “def” keyword in python.
● Parameters are inputs to the function and they are
separated by commas.
● “return” is the keyword for returning the output
● Example:
Computer Science Department, UET Lahore.
Functions: How to Call?
● Functions are called by writing the name of the
function and passing the parameters to the
functions.
● Output of the function is received in a new
variable.
● Example:
Computer Science Department, UET Lahore.
Functions: Previous Example
Computer Science Department, UET Lahore.
Let’s Use Functions to solve the same problem.
Functions: Previous Example
Computer Science Department, UET Lahore.
def calculate_sum():
add = 0
for x in range(0,5,1):
num = int(input("Enter Number: "))
add = add + num
return add
To calculate the sum,
We can use this
function
def calculate_avg(sum):
avg = sum/5
return avg
To calculate the average,
We can use this method
sum = calculate_sum()
print("Mean: ", calculate_avg(sum))
The rest of program
would look like this.
User-Defined Functions:
● These Functions are called user-defined functions
because they are defined by the users.
● For the program’s simplicity and more readability,
users can define as many functions as they want.
Computer Science Department, UET Lahore.
User-Defined Functions: Benefits
● Functions make the code reusable. We can declare
them once and use them multiple times.
● Functions make the program easier as each small
task is divided into a function.
● Functions increase readability.
Computer Science Department, UET Lahore.
Two-types of Functions:
● User-Defined Functions
● Pre-Defined (Library) Functions
Computer Science Department, UET Lahore.
Pre-Defined (Library) Functions:
● Library functions are the built-in functions in
Python programming.
● Programmers can use library functions by invoking
the functions directly; they don't need to write
the functions themselves.
Computer Science Department, UET Lahore.
Functions: Previous Example
Computer Science Department, UET Lahore.
Instead of writing this complete code, Python library (statistics) has
already written this code.
Pre-Defined Functions: Extended
Computer Science Department, UET Lahore.
import statistics
my_list = []
for x in range(0,5,1):
y = int(input("Enter Number: "))
my_list.append(y)
mean = float(statistics.mean(my_list))
print("Mean: ", mean)
Output:
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Mean: 3.0
To calculate the mean,
We can use Pre-defined Functions
Don’t Worry. We will learn
about Lists in Coming Lectures.
Built-in Functions: Python Standard library
Computer Science Department, UET Lahore.
Built-in Functions: with importing math library
Computer Science Department, UET Lahore.
● import maths
Built-in Functions: with importing math library
Computer Science Department, UET Lahore.
● For Example:
Learning Objective
In this lecture, we learnt about functions,
how to define functions with different
parameters, differentiate between built-in
and user-defined functions.
Computer Science Department, UET Lahore.
Conclusion
● A function is a block of organized, reusable code
that is used to perform a single, related action.
● Functions are of 2 types
○ Built-in Functions User-defined
Functions
● Functions can have zero or more parameters.
● Syntax to define and call Functions is as follows:
Computer Science Department, UET Lahore.
Take Home Tasks
1. Create a function that takes the age in years and returns
the age in days.
Note:
● Use 365 days as the length of a year for this challenge.
● Ignore leap years and days between last birthday and now.
● Expect only positive integer inputs.
Examples:
● calcAge(65) ➞ 23725
● calcAge(0) ➞ 0
● calcAge(20) ➞ 7300
Computer Science Department, UET Lahore.

More Related Content

Similar to Updated Week 06 and 07 Functions In Python.pptx

Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
mustafatahertotanawa1
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
NileshBorkar12
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
Ranel Padon
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
Function
FunctionFunction
Function
mshoaib15
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
ethiouniverse
 
The Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxThe Input Statement in Core Python .pptx
The Input Statement in Core Python .pptx
Kavitha713564
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
ziyadaslanbey
 
INTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONINTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHON
vikram mahendra
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notationirdginfo
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
HiHi398889
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Learn C
Learn CLearn C
Learn C
kantila
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
zafar578075
 

Similar to Updated Week 06 and 07 Functions In Python.pptx (20)

Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
Function
FunctionFunction
Function
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
The Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxThe Input Statement in Core Python .pptx
The Input Statement in Core Python .pptx
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
INTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONINTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHON
 
Python functions
Python functionsPython functions
Python functions
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
Learn C
Learn CLearn C
Learn C
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
 

Recently uploaded

Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 

Recently uploaded (20)

Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 

Updated Week 06 and 07 Functions In Python.pptx

  • 2. Learning Objectives ● Explain how to define and write functions ● Illustrate how to call functions ● Analyze how to pass different arguments to functions ● Demonstrate how to return a value from functions Computer Science Department, UET Lahore.
  • 3. Working Example Write a Python Program to calculate the mean of five numbers input by user. Formula for calculating the mean is: For Example: Computer Science Department, UET Lahore. Input: 1, 2, 3, 4 Output: 2.5 Mean = {Sum of numbers} ÷ {Total numbers}
  • 4. Working Example: Solution Computer Science Department, UET Lahore. add = 0 for x in range(0,5,1): num = int(input(“Enter Number: ”)) add = add + num print(“Mean: ”, add/5) Output: Enter Number: 1 Enter Number: 2 Enter Number: 3 Enter Number: 4 Enter Number: 5 Mean: 3.0 To calculate the mean, We can use this method
  • 5. Is there any better Solution? Computer Science Department, UET Lahore. add = 0 for x in range(0,5,1): num = int(input(“Enter Number: ”)) add = add + num print(“Mean: ”, add/5) Output: Enter Number: 1 Enter Number: 2 Enter Number: 3 Enter Number: 4 Enter Number: 5 Mean: 3.0 To calculate the mean, We can use this method
  • 6. Is there any better Solution? Computer Science Department, UET Lahore. ● Better solution in terms of readability and simplicity. ● Yes, there is. ● But before moving to the solution lets take a real life example of Automobile factory.
  • 7. Automobiles in Factory ● How do the automobiles are created in the factory? Computer Science Department, UET Lahore.
  • 8. Components of Automobiles ● Wheels, Brakes, Engine, Steering Wheels etc are the components of the car. Computer Science Department, UET Lahore.
  • 9. Automobiles in Factory ● Wheels, Brakes, Engine, Steering Wheels are manufactured separately and they are assembled in the automobile factory. Computer Science Department, UET Lahore.
  • 10. Functions ● Functions are like short programs that can take input, process on it, and may return the results ● Functions are like building blocks. They let you divide complicated programs into manageable pieces Computer Science Department, UET Lahore.
  • 11. Functions: How to Create? ● Functions are defined using “def” keyword in python. ● Parameters are inputs to the function and they are separated by commas. ● “return” is the keyword for returning the output ● Example: Computer Science Department, UET Lahore.
  • 12. Functions: How to Call? ● Functions are called by writing the name of the function and passing the parameters to the functions. ● Output of the function is received in a new variable. ● Example: Computer Science Department, UET Lahore.
  • 13. Functions: Previous Example Computer Science Department, UET Lahore. Let’s Use Functions to solve the same problem.
  • 14. Functions: Previous Example Computer Science Department, UET Lahore. def calculate_sum(): add = 0 for x in range(0,5,1): num = int(input("Enter Number: ")) add = add + num return add To calculate the sum, We can use this function def calculate_avg(sum): avg = sum/5 return avg To calculate the average, We can use this method sum = calculate_sum() print("Mean: ", calculate_avg(sum)) The rest of program would look like this.
  • 15. User-Defined Functions: ● These Functions are called user-defined functions because they are defined by the users. ● For the program’s simplicity and more readability, users can define as many functions as they want. Computer Science Department, UET Lahore.
  • 16. User-Defined Functions: Benefits ● Functions make the code reusable. We can declare them once and use them multiple times. ● Functions make the program easier as each small task is divided into a function. ● Functions increase readability. Computer Science Department, UET Lahore.
  • 17. Two-types of Functions: ● User-Defined Functions ● Pre-Defined (Library) Functions Computer Science Department, UET Lahore.
  • 18. Pre-Defined (Library) Functions: ● Library functions are the built-in functions in Python programming. ● Programmers can use library functions by invoking the functions directly; they don't need to write the functions themselves. Computer Science Department, UET Lahore.
  • 19. Functions: Previous Example Computer Science Department, UET Lahore. Instead of writing this complete code, Python library (statistics) has already written this code.
  • 20. Pre-Defined Functions: Extended Computer Science Department, UET Lahore. import statistics my_list = [] for x in range(0,5,1): y = int(input("Enter Number: ")) my_list.append(y) mean = float(statistics.mean(my_list)) print("Mean: ", mean) Output: Enter Number: 1 Enter Number: 2 Enter Number: 3 Enter Number: 4 Enter Number: 5 Mean: 3.0 To calculate the mean, We can use Pre-defined Functions Don’t Worry. We will learn about Lists in Coming Lectures.
  • 21. Built-in Functions: Python Standard library Computer Science Department, UET Lahore.
  • 22. Built-in Functions: with importing math library Computer Science Department, UET Lahore. ● import maths
  • 23. Built-in Functions: with importing math library Computer Science Department, UET Lahore. ● For Example:
  • 24. Learning Objective In this lecture, we learnt about functions, how to define functions with different parameters, differentiate between built-in and user-defined functions. Computer Science Department, UET Lahore.
  • 25. Conclusion ● A function is a block of organized, reusable code that is used to perform a single, related action. ● Functions are of 2 types ○ Built-in Functions User-defined Functions ● Functions can have zero or more parameters. ● Syntax to define and call Functions is as follows: Computer Science Department, UET Lahore.
  • 26. Take Home Tasks 1. Create a function that takes the age in years and returns the age in days. Note: ● Use 365 days as the length of a year for this challenge. ● Ignore leap years and days between last birthday and now. ● Expect only positive integer inputs. Examples: ● calcAge(65) ➞ 23725 ● calcAge(0) ➞ 0 ● calcAge(20) ➞ 7300 Computer Science Department, UET Lahore.