SlideShare a Scribd company logo
1 of 18
Download to read offline
Functions and Arguments in
Python
Published on: September 20, 2022
In this article, MarsDevs illustrates functions in Python, the function
argument, and the keyword argument. We use various examples with
code to understand the concept better.
What do we mean by a Function?
A function is a block of code that performs certain defined operations
which can be reused by calling that function. So, a function has a high
degree of code reuse capacity and better modularity.
When a function is created, we define the sequence of steps that should
be performed and return its resultant or performed value to the caller. We
call this function by the name of the function.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Python has already built-in functions like print(), sqrt(), etc. We can also
create our own functions, so created functions by users are called user-
defined functions.
User-defined function and built-in function
Defining a Function
We can create a function by defining the required functionality into it. We
need to remember some rules before creating functions using Python.
These rules are as follows
Starting with the keyword def then naming the function with
parentheses ().
Name of the function should begin with a letter or underscore or
lowercase letters.
Name of the function can have digits but the function name can not
start with a digit.
Name of the function can be in any length and can not be the same
as Python keywords.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
You can define or place input parameters or arguments inside these
parentheses ().
There is an optional statement - docstring or documentation string of
the function.
Then the code block starts after a: after parentheses ().
Return statement is also optional which returns the control to the
caller function.
Syntax of function
There should be positional behavior to return in the same order as they
defined.
Example
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
The function definition consists of name, parameters required and
required step in which manner function should go, then return values, if
any.
def keyword - Tells the compiler that function starts from here.
Function name - Give the function a name to avoid ambiguity and
call using this name.
Parameters - These are the arguments passed to the function and
used in the function processing.
Colon (:) - Marks end of a function declaration
Docstring - This is a comment which tells what this function does.
Docstring makes it easy to understand the code. It’s optional to use.
Statements - These are the steps in the function which dictate what
a function should do.
return - Returns the resultant value or expression to the caller of this
function, if not mentioned it returns None. It’s optional to use.
Calling a function
We call a function by its name with parentheses () and if there are any
parameters then we put those parameters inside these parentheses ().
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Example
Argument Passing Techniques
There are different types of techniques to pass arguments to a function.
We will discuss 2 argument passing techniques here: pass-by-value and
pass-by-reference.
In pass-by-reference, the address of the variables/data structures
are passed by the calling-function, so any changes done by the
called-function in these parameters will be reflected in the original
copy in the calling-function.
In pass-by-value, a copy of only the value of variables/data
structures is passed to the called-function and if there is any change
made by called-function in the copied parameters those will not be
reflected in the original copy in the calling-function.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
In pass-by-reference argument passing technique, when we change
parameters that are referenced from the caller function within a called-
function, the change also reflects back in the calling / original function.
This is because addresses of those parameters are passed instead of
values to the called-function. Python uses this argument passing
technique.
In the pass-by-value argument passing technique, when we change
parameters referenced from caller function within a called-function, the
change does not reflect back in the calling / original function. This is
because only the copies of those values of that argument are passed
instead of addresses.
Function Arguments
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Now, let’s try to understand arguments that are passed to a function.
There are various types of functions arguments
Required/Positional arguments
Keyword arguments
Default arguments
Variable-length arguments
These are explained as following below in brief
1. Required arguments
These arguments should be passed in the correct positional order, so they
should match a number of arguments in the function call with the function
definition. They should be defined in an ordered manner.
Example
The above mess() function requires one argument (name) to pass in
function, there will be an error raised without it, modified example is given
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
as following below
2. Keyword arguments
When you pass these arguments, then the caller identifies the arguments
by parameter name. These are not mandatory to pass the arguments or
place them in order like required/positional arguments. Python
interpreters can identify and match the values with parameters.
Take this example
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
If you want to label them in first_name and last_name in the calling-
function, then you can label as below
Here first_name and last_name are keyword arguments
3. Default arguments
When you do not provide any value for an argument then it assumes a
default value (you can set) in the function call for that argument. Take the
following example
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Note that when you do not know how many a number of arguments
should be passed, then we use two asterisks **name, to map arguments
to a single parameter. Consider the following example
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
4. Variable-length arguments
In this, there could be less number of parameters in the function definition
than the number of arguments passed. These parameters are not named
in the function definition and are known as variable-length arguments. An
example is given below
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Recursive function
Recursive function calls, again and again, the same function till the base
condition is satisfied or stack overflows / memory overflows.
Consider the following recursive function to calculate the factorial of
natural number n.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Anonymous function
These functions are defined without a name and use the “lambda”
keyword instead of “def”, so these are also called as a lambda function.
They return only one value but can have 0 or more arguments.
Syntax is given below
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
If we were to write above logic using normal function, then it would be
Scope of Variables in Python
There are 2 types of variables, based on their scope - Global variable and
Local variable.
1. Global Variable
These variables are declared outside of the functions and can be
accessed globally by any function defined in the main function or
program. These can be accessed inside or outside of the function, i.e
everywhere.
An example is given as follows below
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
2. Local Variable
These variables are declared inside the function and can be accessed
within that function only. These can not be accessed globally.
An example is given as following below
It will print 100 for inside x because the value of x = 100 is defined inside the
fun, so no error.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
It will not print for the outside x and will raise a NameError: that name ‘x’ is
not defined.
Note that when you define both x inside and outside of the function, then it
will prioritize local x over global. It means the local variable has a higher
priority to access than the global variable if both local and global exist. An
example is given below.
Pass Statement
A function can not be empty, to avoid any errors we use ‘pass’ statement.
Can be used as a placeholder as well.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Our Office Location
INDIA
Jijai Nagar, Kothrud, Pune
(IN) - 411038
Phone: +91 9322358095
USA
3422, Old Capitol Trail, Suite 93,Wilmington, DE 19808
Phone: +1 (302) 216 - 9560
Subscribe Us
© 2019-2023 MarsDevs, All rights reserved
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com

More Related Content

Similar to Functions and Arguments in Python

Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdfalaparthi
 
Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfDeeptiMalhotra19
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Dynamic website
Dynamic websiteDynamic website
Dynamic websitesalissal
 
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.pdfSudhanshiBakre1
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Sar
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuplesMalligaarjunanN
 

Similar to Functions and Arguments in Python (20)

Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
 
Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdf
 
Python functions
Python   functionsPython   functions
Python functions
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
functions new.pptx
functions new.pptxfunctions new.pptx
functions new.pptx
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
 
topic_perlcgi
topic_perlcgitopic_perlcgi
topic_perlcgi
 
topic_perlcgi
topic_perlcgitopic_perlcgi
topic_perlcgi
 
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
 
4. function
4. function4. function
4. function
 
Python-Functions.pptx
Python-Functions.pptxPython-Functions.pptx
Python-Functions.pptx
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Compose Camp - Session1.pdf
Compose Camp - Session1.pdfCompose Camp - Session1.pdf
Compose Camp - Session1.pdf
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 

More from Mars Devs

The Rise & Impact of PWA Adoption in 2024
The Rise & Impact of PWA Adoption in 2024The Rise & Impact of PWA Adoption in 2024
The Rise & Impact of PWA Adoption in 2024Mars Devs
 
Dive into the Battle of Titans Agile vs. Waterfall.pdf
Dive into the Battle of Titans Agile vs. Waterfall.pdfDive into the Battle of Titans Agile vs. Waterfall.pdf
Dive into the Battle of Titans Agile vs. Waterfall.pdfMars Devs
 
Kotlin - A Beginner’s Guide__________________
Kotlin - A Beginner’s Guide__________________Kotlin - A Beginner’s Guide__________________
Kotlin - A Beginner’s Guide__________________Mars Devs
 
A Sneak Peek Into Drupal - A Beginner’s Guide.pdf
A Sneak Peek Into Drupal - A Beginner’s Guide.pdfA Sneak Peek Into Drupal - A Beginner’s Guide.pdf
A Sneak Peek Into Drupal - A Beginner’s Guide.pdfMars Devs
 
Master Clean and Minimalist Design with The Golden Rules!.pdf
Master Clean and Minimalist Design with The Golden Rules!.pdfMaster Clean and Minimalist Design with The Golden Rules!.pdf
Master Clean and Minimalist Design with The Golden Rules!.pdfMars Devs
 
Python VS Java___________________________
Python VS Java___________________________Python VS Java___________________________
Python VS Java___________________________Mars Devs
 
6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf
6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf
6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdfMars Devs
 
Everything Technical on List in Python--
Everything Technical on List in Python--Everything Technical on List in Python--
Everything Technical on List in Python--Mars Devs
 
6 Best OpenAPI Documentation Tools that You must Know
6 Best OpenAPI Documentation Tools that You must Know6 Best OpenAPI Documentation Tools that You must Know
6 Best OpenAPI Documentation Tools that You must KnowMars Devs
 
Learn Django Tips, Tricks & Techniques for Developers
Learn Django Tips, Tricks & Techniques for DevelopersLearn Django Tips, Tricks & Techniques for Developers
Learn Django Tips, Tricks & Techniques for DevelopersMars Devs
 
What is Docker & Why is it Getting Popular?
What is Docker & Why is it Getting Popular?What is Docker & Why is it Getting Popular?
What is Docker & Why is it Getting Popular?Mars Devs
 
How to Use CodePen - Learn with us!
How to Use CodePen - Learn with us!How to Use CodePen - Learn with us!
How to Use CodePen - Learn with us!Mars Devs
 
Chrome Developer Tools - Pro Tips & Tricks
Chrome Developer Tools - Pro Tips & TricksChrome Developer Tools - Pro Tips & Tricks
Chrome Developer Tools - Pro Tips & TricksMars Devs
 
10 Best Front-end Frameworks for Web Development
10 Best Front-end Frameworks for Web Development10 Best Front-end Frameworks for Web Development
10 Best Front-end Frameworks for Web DevelopmentMars Devs
 
What is Json?
What is Json?What is Json?
What is Json?Mars Devs
 
Figma Community Files that are Absolute Gold!
Figma Community Files that are Absolute Gold!Figma Community Files that are Absolute Gold!
Figma Community Files that are Absolute Gold!Mars Devs
 
AI Tools to Reduce Hardwork
AI Tools to Reduce HardworkAI Tools to Reduce Hardwork
AI Tools to Reduce HardworkMars Devs
 
Introduction to Python Pandas
Introduction to Python PandasIntroduction to Python Pandas
Introduction to Python PandasMars Devs
 
Graphic Design Trends in 2023
Graphic Design Trends in 2023Graphic Design Trends in 2023
Graphic Design Trends in 2023Mars Devs
 
MarsDevs Predicts The Python Trends for 2023
MarsDevs Predicts The Python Trends for 2023MarsDevs Predicts The Python Trends for 2023
MarsDevs Predicts The Python Trends for 2023Mars Devs
 

More from Mars Devs (20)

The Rise & Impact of PWA Adoption in 2024
The Rise & Impact of PWA Adoption in 2024The Rise & Impact of PWA Adoption in 2024
The Rise & Impact of PWA Adoption in 2024
 
Dive into the Battle of Titans Agile vs. Waterfall.pdf
Dive into the Battle of Titans Agile vs. Waterfall.pdfDive into the Battle of Titans Agile vs. Waterfall.pdf
Dive into the Battle of Titans Agile vs. Waterfall.pdf
 
Kotlin - A Beginner’s Guide__________________
Kotlin - A Beginner’s Guide__________________Kotlin - A Beginner’s Guide__________________
Kotlin - A Beginner’s Guide__________________
 
A Sneak Peek Into Drupal - A Beginner’s Guide.pdf
A Sneak Peek Into Drupal - A Beginner’s Guide.pdfA Sneak Peek Into Drupal - A Beginner’s Guide.pdf
A Sneak Peek Into Drupal - A Beginner’s Guide.pdf
 
Master Clean and Minimalist Design with The Golden Rules!.pdf
Master Clean and Minimalist Design with The Golden Rules!.pdfMaster Clean and Minimalist Design with The Golden Rules!.pdf
Master Clean and Minimalist Design with The Golden Rules!.pdf
 
Python VS Java___________________________
Python VS Java___________________________Python VS Java___________________________
Python VS Java___________________________
 
6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf
6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf
6 Steps Functionality Hacks To Kubernetes - 2023 Update.pdf
 
Everything Technical on List in Python--
Everything Technical on List in Python--Everything Technical on List in Python--
Everything Technical on List in Python--
 
6 Best OpenAPI Documentation Tools that You must Know
6 Best OpenAPI Documentation Tools that You must Know6 Best OpenAPI Documentation Tools that You must Know
6 Best OpenAPI Documentation Tools that You must Know
 
Learn Django Tips, Tricks & Techniques for Developers
Learn Django Tips, Tricks & Techniques for DevelopersLearn Django Tips, Tricks & Techniques for Developers
Learn Django Tips, Tricks & Techniques for Developers
 
What is Docker & Why is it Getting Popular?
What is Docker & Why is it Getting Popular?What is Docker & Why is it Getting Popular?
What is Docker & Why is it Getting Popular?
 
How to Use CodePen - Learn with us!
How to Use CodePen - Learn with us!How to Use CodePen - Learn with us!
How to Use CodePen - Learn with us!
 
Chrome Developer Tools - Pro Tips & Tricks
Chrome Developer Tools - Pro Tips & TricksChrome Developer Tools - Pro Tips & Tricks
Chrome Developer Tools - Pro Tips & Tricks
 
10 Best Front-end Frameworks for Web Development
10 Best Front-end Frameworks for Web Development10 Best Front-end Frameworks for Web Development
10 Best Front-end Frameworks for Web Development
 
What is Json?
What is Json?What is Json?
What is Json?
 
Figma Community Files that are Absolute Gold!
Figma Community Files that are Absolute Gold!Figma Community Files that are Absolute Gold!
Figma Community Files that are Absolute Gold!
 
AI Tools to Reduce Hardwork
AI Tools to Reduce HardworkAI Tools to Reduce Hardwork
AI Tools to Reduce Hardwork
 
Introduction to Python Pandas
Introduction to Python PandasIntroduction to Python Pandas
Introduction to Python Pandas
 
Graphic Design Trends in 2023
Graphic Design Trends in 2023Graphic Design Trends in 2023
Graphic Design Trends in 2023
 
MarsDevs Predicts The Python Trends for 2023
MarsDevs Predicts The Python Trends for 2023MarsDevs Predicts The Python Trends for 2023
MarsDevs Predicts The Python Trends for 2023
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 

Recently uploaded (20)

Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 

Functions and Arguments in Python

  • 1. Functions and Arguments in Python Published on: September 20, 2022 In this article, MarsDevs illustrates functions in Python, the function argument, and the keyword argument. We use various examples with code to understand the concept better. What do we mean by a Function? A function is a block of code that performs certain defined operations which can be reused by calling that function. So, a function has a high degree of code reuse capacity and better modularity. When a function is created, we define the sequence of steps that should be performed and return its resultant or performed value to the caller. We call this function by the name of the function. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 2. Python has already built-in functions like print(), sqrt(), etc. We can also create our own functions, so created functions by users are called user- defined functions. User-defined function and built-in function Defining a Function We can create a function by defining the required functionality into it. We need to remember some rules before creating functions using Python. These rules are as follows Starting with the keyword def then naming the function with parentheses (). Name of the function should begin with a letter or underscore or lowercase letters. Name of the function can have digits but the function name can not start with a digit. Name of the function can be in any length and can not be the same as Python keywords. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 3. You can define or place input parameters or arguments inside these parentheses (). There is an optional statement - docstring or documentation string of the function. Then the code block starts after a: after parentheses (). Return statement is also optional which returns the control to the caller function. Syntax of function There should be positional behavior to return in the same order as they defined. Example Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 4. The function definition consists of name, parameters required and required step in which manner function should go, then return values, if any. def keyword - Tells the compiler that function starts from here. Function name - Give the function a name to avoid ambiguity and call using this name. Parameters - These are the arguments passed to the function and used in the function processing. Colon (:) - Marks end of a function declaration Docstring - This is a comment which tells what this function does. Docstring makes it easy to understand the code. It’s optional to use. Statements - These are the steps in the function which dictate what a function should do. return - Returns the resultant value or expression to the caller of this function, if not mentioned it returns None. It’s optional to use. Calling a function We call a function by its name with parentheses () and if there are any parameters then we put those parameters inside these parentheses (). Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 5. Example Argument Passing Techniques There are different types of techniques to pass arguments to a function. We will discuss 2 argument passing techniques here: pass-by-value and pass-by-reference. In pass-by-reference, the address of the variables/data structures are passed by the calling-function, so any changes done by the called-function in these parameters will be reflected in the original copy in the calling-function. In pass-by-value, a copy of only the value of variables/data structures is passed to the called-function and if there is any change made by called-function in the copied parameters those will not be reflected in the original copy in the calling-function. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 6. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 7. In pass-by-reference argument passing technique, when we change parameters that are referenced from the caller function within a called- function, the change also reflects back in the calling / original function. This is because addresses of those parameters are passed instead of values to the called-function. Python uses this argument passing technique. In the pass-by-value argument passing technique, when we change parameters referenced from caller function within a called-function, the change does not reflect back in the calling / original function. This is because only the copies of those values of that argument are passed instead of addresses. Function Arguments Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 8. Now, let’s try to understand arguments that are passed to a function. There are various types of functions arguments Required/Positional arguments Keyword arguments Default arguments Variable-length arguments These are explained as following below in brief 1. Required arguments These arguments should be passed in the correct positional order, so they should match a number of arguments in the function call with the function definition. They should be defined in an ordered manner. Example The above mess() function requires one argument (name) to pass in function, there will be an error raised without it, modified example is given Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 9. as following below 2. Keyword arguments When you pass these arguments, then the caller identifies the arguments by parameter name. These are not mandatory to pass the arguments or place them in order like required/positional arguments. Python interpreters can identify and match the values with parameters. Take this example Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 10. If you want to label them in first_name and last_name in the calling- function, then you can label as below Here first_name and last_name are keyword arguments 3. Default arguments When you do not provide any value for an argument then it assumes a default value (you can set) in the function call for that argument. Take the following example Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 11. Note that when you do not know how many a number of arguments should be passed, then we use two asterisks **name, to map arguments to a single parameter. Consider the following example Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 12. 4. Variable-length arguments In this, there could be less number of parameters in the function definition than the number of arguments passed. These parameters are not named in the function definition and are known as variable-length arguments. An example is given below Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 13. Recursive function Recursive function calls, again and again, the same function till the base condition is satisfied or stack overflows / memory overflows. Consider the following recursive function to calculate the factorial of natural number n. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 14. Anonymous function These functions are defined without a name and use the “lambda” keyword instead of “def”, so these are also called as a lambda function. They return only one value but can have 0 or more arguments. Syntax is given below Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 15. If we were to write above logic using normal function, then it would be Scope of Variables in Python There are 2 types of variables, based on their scope - Global variable and Local variable. 1. Global Variable These variables are declared outside of the functions and can be accessed globally by any function defined in the main function or program. These can be accessed inside or outside of the function, i.e everywhere. An example is given as follows below Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 16. 2. Local Variable These variables are declared inside the function and can be accessed within that function only. These can not be accessed globally. An example is given as following below It will print 100 for inside x because the value of x = 100 is defined inside the fun, so no error. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 17. It will not print for the outside x and will raise a NameError: that name ‘x’ is not defined. Note that when you define both x inside and outside of the function, then it will prioritize local x over global. It means the local variable has a higher priority to access than the global variable if both local and global exist. An example is given below. Pass Statement A function can not be empty, to avoid any errors we use ‘pass’ statement. Can be used as a placeholder as well. Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  • 18. Our Office Location INDIA Jijai Nagar, Kothrud, Pune (IN) - 411038 Phone: +91 9322358095 USA 3422, Old Capitol Trail, Suite 93,Wilmington, DE 19808 Phone: +1 (302) 216 - 9560 Subscribe Us © 2019-2023 MarsDevs, All rights reserved Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com