SlideShare a Scribd company logo
Functions in Python
Syntax of Function
def function_name(arguments):
"""docstring"""
statement(s)
• Keyword def marks the start of function header.
• arguments through which we pass values to a function. They are optional.
• A colon (:) to mark the starting of function
• Optional documentation string (docstring) to describe what the function does.
• One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.
Defining and Calling Functions
Step 1: Declare the function with the keyword def followed by the function name.
Step 2: Write the arguments inside the opening and closing parentheses of the
function, and end the declaration with a colon.
Step 3: Add the program statements to be executed.
Step 4: End the function with/without return statement.
Ex:
def hello():
print("Hello, World!") #statements inside function
hello() #function calling
Example of Function that takes one string arguments
def greet(name):
"""This function greets to the person passed in as parameter"""
print("Hello, " + name + ". Good morning!")
greet('vani') #function calling
Output:
Hello, vani. Good morning!
print(greet.__doc__)
Output:
This function greets to the person passed into the name parameter
return statement
The return statement is used to exit a function and go back to the place
from where it was called.
the return statement itself is not present inside a function, then the
function will return the None object.
def absolute_value(num):
if num >= 0:
return num
else:
return -num
print(absolute_value(2)) Output: 2
print(absolute_value(-4)) Output: 4
Return multiple values
def add_numbers(x, y, z):
a = x + y
b = x + z
c = y + z
return a, b, c
sums = add_numbers(1, 2, 3)
print(sums)
Output
(3, 4, 5)
Functions exit immediately when they hit a
return statement
def loop_five():
for x in range(0, 25):
print(x)
if x == 5:
# Stop function at x == 5
return
print("This line will not execute.")
loop_five()
Using main() as a Function
def hello():
print("Hello, World!")
def main():
print("This is the main function.")
hello()
main()
Output:
This is the main function.
Hello, World!
def sum():
a=15 #local variable
b=8
print("in fun", a)
sum()
print("outside", a)
$python3 main.py
in fun 15
Traceback (most recent call last): File "main.py", line 8, in <module> print("outside",
a) NameError: name 'a' is not defined
a=15
def sum():
b=8
print("in fun", a)
sum()
print("outside", a)
$python3 main.py
in fun 15
outside 15
a=15
def sum():
a=10
b=8
print("in fun", a)
sum()
print("outside", a)
a=15
def sum():
global a
a=10
b=8
print("in fun", a)
sum()
print("outside", a)
Scope of a Variable: Local and Global Variables
In the next program we’ll declare a global variable and modify our
original names() function so that the instructions are in two discrete
functions.
The first function, has_vowel() will check to see if the name string
contains a vowel.
The second function print_letters() will print each letter of the name
string.
name = str(input('Enter your name: ')) # Declare global variable name for use in all functions
# Define function to check if name contains a vowel
def has_vowel():
if set('aeiou').intersection(name.lower()):
print('Your name contains a vowel.')
else:
print('Your name does not contain a vowel.')
def print_letters(): # Iterate over letters in name string
for letter in name:
print(letter)
def main(): # Define main method that calls other functions
has_vowel()
print_letters()
main() # calling main() function
Four types of function arguments.
• Default Arguments
• Required Arguments
• Keyword Arguments
• Arbitrary Arguments
Default arguments example
Default values indicate that the function argument will take
that value if no argument value is passed during function call.
The default value is assigned by using assignment (=) operator.
Here, msg parameter has a default value Good morning!.
def greet(name, msg = "Good morning!"):
print("Hello",name + ', ' + msg)
greet("Kate")
greet("Bruce","How do you do?")
Required Arguments
Required arguments are the mandatory arguments of a function.
def greet(name,msg):
print("Hello",name + ', ' + msg)
greet("Monica","Good morning!")
>>> greet("Monica") # only one argument
TypeError: greet() missing 1 required positional argument: 'msg'
Keyword arguments example
The keywords are mentioned during the function call along with their
corresponding values. These keywords are mapped with the function
arguments so the function can easily identify the corresponding values
even if the order is not maintained during the function call.
def greet(name, msg):
print("Hello",name + ', ' + msg)
greet(msg = "How do you do?",name = "Bruce")
Variable number of arguments example
we can have a design where any number of arguments can be passed based on the
requirement.
def greet(*names):
for name in names:
print("Hello",name)
greet("Monica","Luke","Steve","John")
Output
Hello Monica
Hello Luke
Hello Steve
Hello John
def sum(a,*b):
for i in b:
print(i)
sum(5,6,7.3)
# output:
6
7.3
def person(a,**b):
for i,j in b.items():
print(i,j);
person(5,age=18,mob=9542352)
Output:
age 18
mob 9542352

More Related Content

PDF
Python Function
Soba Arjun
 
PDF
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
PDF
Functions in python
Ilian Iliev
 
PPTX
Python PCEP Function Parameters
IHTMINSTITUTE
 
PPT
php 2 Function creating, calling, PHP built-in function
tumetr1
 
PDF
Introduction to Python decorators
rikbyte
 
PDF
Introduction to python
Marian Marinov
 
PDF
Class 7a: Functions
Marc Gouw
 
Python Function
Soba Arjun
 
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Functions in python
Ilian Iliev
 
Python PCEP Function Parameters
IHTMINSTITUTE
 
php 2 Function creating, calling, PHP built-in function
tumetr1
 
Introduction to Python decorators
rikbyte
 
Introduction to python
Marian Marinov
 
Class 7a: Functions
Marc Gouw
 

What's hot (20)

PPTX
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
P3 InfoTech Solutions Pvt. Ltd.
 
PPT
Php Reusing Code And Writing Functions
mussawir20
 
PDF
Preparing for the next PHP version (5.6)
Damien Seguy
 
PDF
Functions in PHP
Vineet Kumar Saini
 
PDF
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
PPTX
Python programming workshop session 1
Abdul Haseeb
 
PPTX
Php string function
Ravi Bhadauria
 
PDF
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
PDF
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
PDF
An Introduction to Functional Programming - DeveloperUG - 20140311
Andreas Pauley
 
PPTX
F# Eye For The C# Guy - f(by) Minsk 2014
Phillip Trelford
 
PDF
Swift 3.0 の新しい機能(のうちの9つ)
Tomohiro Kumagai
 
PDF
Zend Certification Preparation Tutorial
Lorna Mitchell
 
PDF
ScalaFlavor4J
Kazuhiro Sera
 
PPTX
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
PDF
Functions
Marieswaran Ramasamy
 
PDF
Practice exam php
Yesenia Sánchez Sosa
 
PDF
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
PDF
Time for Functions
simontcousins
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
P3 InfoTech Solutions Pvt. Ltd.
 
Php Reusing Code And Writing Functions
mussawir20
 
Preparing for the next PHP version (5.6)
Damien Seguy
 
Functions in PHP
Vineet Kumar Saini
 
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
Python programming workshop session 1
Abdul Haseeb
 
Php string function
Ravi Bhadauria
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
An Introduction to Functional Programming - DeveloperUG - 20140311
Andreas Pauley
 
F# Eye For The C# Guy - f(by) Minsk 2014
Phillip Trelford
 
Swift 3.0 の新しい機能(のうちの9つ)
Tomohiro Kumagai
 
Zend Certification Preparation Tutorial
Lorna Mitchell
 
ScalaFlavor4J
Kazuhiro Sera
 
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
Practice exam php
Yesenia Sánchez Sosa
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
Time for Functions
simontcousins
 
Ad

Similar to Functions in python3 (20)

PPTX
Working with functions.pptx. Hb.
sabarivelan111007
 
PPTX
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
PPT
functions _
SwatiHans10
 
PPTX
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
PPT
Function in Python [Autosaved].ppt
GaganvirKaur
 
PPTX
Functions in Python with all type of arguments
riazahamed37
 
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
PPTX
Python Learn Function with example programs
GeethaPanneer
 
PPTX
Python functions part12
Vishal Dutt
 
PDF
Python basic
Saifuddin Kaijar
 
PPTX
Pythonlearn-04-Functions (1).pptx
leavatin
 
PPTX
Python for Data Science function third module ppt.pptx
bmit1
 
PDF
Chapter Functions for grade 12 computer Science
KrithikaTM
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PPTX
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
PPTX
Python Details Functions Description.pptx
2442230910
 
PDF
beginners_python_cheat_sheet_pcc_functions.pdf
GuarachandarChand
 
PPTX
Lecture 08.pptx
Mohammad Hassan
 
Working with functions.pptx. Hb.
sabarivelan111007
 
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
functions _
SwatiHans10
 
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
Function in Python [Autosaved].ppt
GaganvirKaur
 
Functions in Python with all type of arguments
riazahamed37
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
Python Learn Function with example programs
GeethaPanneer
 
Python functions part12
Vishal Dutt
 
Python basic
Saifuddin Kaijar
 
Pythonlearn-04-Functions (1).pptx
leavatin
 
Python for Data Science function third module ppt.pptx
bmit1
 
Chapter Functions for grade 12 computer Science
KrithikaTM
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Functions in Python Programming Language
BeulahS2
 
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Python Details Functions Description.pptx
2442230910
 
beginners_python_cheat_sheet_pcc_functions.pdf
GuarachandarChand
 
Lecture 08.pptx
Mohammad Hassan
 
Ad

More from Lakshmi Sarvani Videla (20)

DOCX
Data Science Using Python
Lakshmi Sarvani Videla
 
DOCX
Programs on multithreading
Lakshmi Sarvani Videla
 
PPT
Menu Driven programs in Java
Lakshmi Sarvani Videla
 
DOCX
Recursion in C
Lakshmi Sarvani Videla
 
DOCX
Simple questions on structures concept
Lakshmi Sarvani Videla
 
PPTX
Errors incompetitiveprogramming
Lakshmi Sarvani Videla
 
DOCX
Relational Operators in C
Lakshmi Sarvani Videla
 
PPTX
Recursive functions in C
Lakshmi Sarvani Videla
 
PPTX
Function Pointer in C
Lakshmi Sarvani Videla
 
PPTX
Functions
Lakshmi Sarvani Videla
 
DOCX
Java sessionnotes
Lakshmi Sarvani Videla
 
DOCX
Singlelinked list
Lakshmi Sarvani Videla
 
PPTX
Dictionary
Lakshmi Sarvani Videla
 
DOCX
DataStructures notes
Lakshmi Sarvani Videla
 
DOCX
Solutionsfor co2 C Programs for data structures
Lakshmi Sarvani Videla
 
DOCX
C programs
Lakshmi Sarvani Videla
 
Data Science Using Python
Lakshmi Sarvani Videla
 
Programs on multithreading
Lakshmi Sarvani Videla
 
Menu Driven programs in Java
Lakshmi Sarvani Videla
 
Recursion in C
Lakshmi Sarvani Videla
 
Simple questions on structures concept
Lakshmi Sarvani Videla
 
Errors incompetitiveprogramming
Lakshmi Sarvani Videla
 
Relational Operators in C
Lakshmi Sarvani Videla
 
Recursive functions in C
Lakshmi Sarvani Videla
 
Function Pointer in C
Lakshmi Sarvani Videla
 
Java sessionnotes
Lakshmi Sarvani Videla
 
Singlelinked list
Lakshmi Sarvani Videla
 
DataStructures notes
Lakshmi Sarvani Videla
 
Solutionsfor co2 C Programs for data structures
Lakshmi Sarvani Videla
 

Recently uploaded (20)

PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Doc9.....................................
SofiaCollazos
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Software Development Methodologies in 2025
KodekX
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 

Functions in python3

  • 2. Syntax of Function def function_name(arguments): """docstring""" statement(s) • Keyword def marks the start of function header. • arguments through which we pass values to a function. They are optional. • A colon (:) to mark the starting of function • Optional documentation string (docstring) to describe what the function does. • One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces). • An optional return statement to return a value from the function.
  • 3. Defining and Calling Functions Step 1: Declare the function with the keyword def followed by the function name. Step 2: Write the arguments inside the opening and closing parentheses of the function, and end the declaration with a colon. Step 3: Add the program statements to be executed. Step 4: End the function with/without return statement. Ex: def hello(): print("Hello, World!") #statements inside function hello() #function calling
  • 4. Example of Function that takes one string arguments def greet(name): """This function greets to the person passed in as parameter""" print("Hello, " + name + ". Good morning!") greet('vani') #function calling Output: Hello, vani. Good morning! print(greet.__doc__) Output: This function greets to the person passed into the name parameter
  • 5. return statement The return statement is used to exit a function and go back to the place from where it was called. the return statement itself is not present inside a function, then the function will return the None object. def absolute_value(num): if num >= 0: return num else: return -num print(absolute_value(2)) Output: 2 print(absolute_value(-4)) Output: 4
  • 6. Return multiple values def add_numbers(x, y, z): a = x + y b = x + z c = y + z return a, b, c sums = add_numbers(1, 2, 3) print(sums) Output (3, 4, 5)
  • 7. Functions exit immediately when they hit a return statement def loop_five(): for x in range(0, 25): print(x) if x == 5: # Stop function at x == 5 return print("This line will not execute.") loop_five()
  • 8. Using main() as a Function def hello(): print("Hello, World!") def main(): print("This is the main function.") hello() main() Output: This is the main function. Hello, World!
  • 9. def sum(): a=15 #local variable b=8 print("in fun", a) sum() print("outside", a) $python3 main.py in fun 15 Traceback (most recent call last): File "main.py", line 8, in <module> print("outside", a) NameError: name 'a' is not defined a=15 def sum(): b=8 print("in fun", a) sum() print("outside", a) $python3 main.py in fun 15 outside 15 a=15 def sum(): a=10 b=8 print("in fun", a) sum() print("outside", a) a=15 def sum(): global a a=10 b=8 print("in fun", a) sum() print("outside", a) Scope of a Variable: Local and Global Variables
  • 10. In the next program we’ll declare a global variable and modify our original names() function so that the instructions are in two discrete functions. The first function, has_vowel() will check to see if the name string contains a vowel. The second function print_letters() will print each letter of the name string.
  • 11. name = str(input('Enter your name: ')) # Declare global variable name for use in all functions # Define function to check if name contains a vowel def has_vowel(): if set('aeiou').intersection(name.lower()): print('Your name contains a vowel.') else: print('Your name does not contain a vowel.') def print_letters(): # Iterate over letters in name string for letter in name: print(letter) def main(): # Define main method that calls other functions has_vowel() print_letters() main() # calling main() function
  • 12. Four types of function arguments. • Default Arguments • Required Arguments • Keyword Arguments • Arbitrary Arguments
  • 13. Default arguments example Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Here, msg parameter has a default value Good morning!. def greet(name, msg = "Good morning!"): print("Hello",name + ', ' + msg) greet("Kate") greet("Bruce","How do you do?")
  • 14. Required Arguments Required arguments are the mandatory arguments of a function. def greet(name,msg): print("Hello",name + ', ' + msg) greet("Monica","Good morning!") >>> greet("Monica") # only one argument TypeError: greet() missing 1 required positional argument: 'msg'
  • 15. Keyword arguments example The keywords are mentioned during the function call along with their corresponding values. These keywords are mapped with the function arguments so the function can easily identify the corresponding values even if the order is not maintained during the function call. def greet(name, msg): print("Hello",name + ', ' + msg) greet(msg = "How do you do?",name = "Bruce")
  • 16. Variable number of arguments example we can have a design where any number of arguments can be passed based on the requirement. def greet(*names): for name in names: print("Hello",name) greet("Monica","Luke","Steve","John") Output Hello Monica Hello Luke Hello Steve Hello John
  • 17. def sum(a,*b): for i in b: print(i) sum(5,6,7.3) # output: 6 7.3 def person(a,**b): for i,j in b.items(): print(i,j); person(5,age=18,mob=9542352) Output: age 18 mob 9542352