Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

Python Functions

The document discusses functions in Python including how to define, call and pass parameters to functions. It provides examples of different types of parameters such as required, keyword, arbitrary etc. and how to use them in function definitions and calls.

Uploaded by

Studyopedia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Python Functions

The document discusses functions in Python including how to define, call and pass parameters to functions. It provides examples of different types of parameters such as required, keyword, arbitrary etc. and how to use them in function definitions and calls.

Uploaded by

Studyopedia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia

Functions in Python with Examples


A function in Python is an organized block of reusable code, which avoid repeating the tasks again and
again. If you want to do a task repeatedly in a code, then just make a function, set the task in it and call
the function multiple times whenever you need it. Functions in Python begins with the keyword def and is
followed by the name of the function and parentheses.

Create a function in Python


Functions in Python, use the def keyword as in the below syntax:

 
def function_name( parameters ):
    function_suite
    return [expression]
 

Above,

The def keyword is used to define a function name,


The parameters are optional to add,
To return a value, the return statement is used.

Note: We will run below example programs in Python to understand the concept of Functions in Python.

Call a function in Python
Code is structured when we define a function. Execution of this function is done by calling. Functions in
https://studyopedia.com/python3/functions-in-python/ 3/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia

Python works the same as in any other programming language. To call, the function name is followed by
parentheses.

Let us see an example and create a function studyopedia and call it in Python:

 
#!/usr/bin/python
 
# Defining a Function i.e. Function Definition
def studyopedia( ):
  print("We provide free tutorials and interview questions.");
  print("We also provide interview questions and answers with quizzes to polish the skills.");
 
# call the studyopedia function
studyopedia()
 

The output is as follows:

 
We provide free tutorials and interview questions.
We also provide interview questions and answers with quizzes to polish the skills.
 

In the above example, we created a function named studyopedia()  and added two print statements in it.
The text in tis statements are visible only when the studyopedia() function is called:

Function Parameters
The names entered in the function at the time of defining it, are Function Parameters. Adding Parameters
to a function in Python is optional. Let us see the syntax for Function Parameters in Python:

 
def function_name(parameter1, parameter2, … ):
 

https://studyopedia.com/python3/functions-in-python/ 4/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia

Above, parameter1, parameter2 are the parameters which is added to the function while defining it. Let
us now see the above example and add a parameter to it:

 
#!/usr/bin/python
 
# Defining a Function i.e. Function Definition with parameter mystr
def studyopedia(mystr):
  print("Device:",mystr);
 
# call the studyopedia function
studyopedia("Laptop")
 
#call again
studyopedia("Desktop")
 

The output is as follows:

 
Device: Laptop
Device: Desktop
 

The above function takes a string mystr as parameter. The string “Device:” is passed along the device
name i.e. Laptop and Desktop.

Function Arguments in Python


In Python,

Required arguments
Keyword arguments 
Arbitrary Keyword Arguments
Default arguments
Variable-length/ Arbitrary arguments
https://studyopedia.com/python3/functions-in-python/ 5/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia
Variable length/ Arbitrary arguments

Let us learn about the above types of Function Arguments, one by one,

Required arguments in Python


The required arguments as the name suggests, is the required number of arguments to be passed on
function call. When you call a function, the arguments in the call is to match with the function definition for
the program to run correctly. Error occurs even if the position of the argument is changed.

Let us see an example wherein we have two argument and we are calling with the same number and
position of arguments:

 
#!/usr/bin/python
 
# Defining a Function with parameters l and b
# length for length and b for breadth of a rectangle
def area(l,b):
  print("Area of Rectangle = ",l*b);
 
# call the area() function
area(20, 30)
 

The output is as follows:

 
Area of Rectangle = 600
 


Keyword arguments in Python
Call a function with keyword arguments in Python. Through this, you can skip arguments or even pass
them in any order while calling a function. As we saw above, this is definitely different that Required
https://studyopedia.com/python3/functions-in-python/ 6/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia

arguments wherein the order in which the arguments are passed is the same while calling.

Let us see an example wherein we are calling the function with two arguments passed in random order:

 
#!/usr/bin/python
 
# Defining a Function with parameters name and rank
def details(name,rank):
  print("Student Name = ",name);
  print("Student Rank = ",rank);
 
# Call the details() function with arguments passed in any order
details(rank = 5, name = "Jack")
 

The output is as follows:

 
Student Name = Jack
Student Rank = 5
 

Let us see another wherein we are calling the function with three arguments passed in random order:

 
#!/usr/bin/python
 
# Defining a Function with parameters product, pid, price
def details(name, pid, price):
  print("Produce Name = ",name);
  print("Product ID = ",pid);
  print("Product Price = ",price);
 
# Call the details() function with arguments passed in random order
details(price = 550.50, name = "Jack", pid = 567) 
 

The output is as follows:

https://studyopedia.com/python3/functions-in-python/ 7/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia

 
Produce Name = Jack
Product ID = 567
Product Price = 550.5
 

Default arguments in Python


While calling a function, if the value isn’t passed, a default value is assumed for that argument. Let us see
an example and display default value. We have a function below with total 2 arguments:

 
#!/usr/bin/python
 
# Defining a Function with parameters name and rank
def details(name,rank = 10):
  print("Student Name = ",name);
  print("Student Rank = ",rank);
 
# Call the details() function
details(name = "John", rank = 5)
details(name = "Mark", rank = 8)
 
# Default value assumed for rank parameter
# since we haven't passed value for rank
details(name = "Jacob")
 

The output is as follows:

 
Student Name = John
Student Rank = 5
Student Name = Mark
Student Rank = 8
Student Name = Jacob
Student Rank = 10 
 

Let us now see another example wherein default value is assumed for the argument, whose value isn’t
specified We have a function below with total 3 arguments:
https://studyopedia.com/python3/functions-in-python/ 8/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia
specified. We have a function below with total 3 arguments:

 
#!/usr/bin/python
 
## Defining a Function with parameters name, rank amd score
def details(name,rank = 10, score = 60.50):
  print("Student Name = ",name);
  print("Student Rank = ",rank);
  print("Student Score = ",score);
  print("----------------------");
 
## Call the details() function
 
# All the values passed while calling
details(name = "John", rank = 5, score = 20.50)
 
# Default value assumed for score parameter
# since we haven't passed value
details(name = "Mark", rank = 8)
 
# Default value assumed for rank and score parameter
# since we haven't passed values for both
details(name = "Jacob")
 

The output is as follows:

 
Student Name = John
Student Rank = 5
Student Score = 20.5
----------------------
Student Name = Mark
Student Rank = 8
Student Score = 60.5
----------------------
Student Name = Jacob
Student Rank = 10
Student Score = 60.5
---------------------- 
 

Variable-length/ Arbitrary arguments in Python (*args)


https://studyopedia.com/python3/functions-in-python/ 9/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia

Arbitrary arguments work when you have no idea about the number of arguments to be passed. These
are variable length arguments, allowing you to pass any number of arguments, defined as * (asterisk).
That means, include a * before the parameter name while defining the function. Let us now see an
example:

 
#!/usr/bin/python
 
## Defining a Function with variable number of arguments
def demo(*sports):
  print("Sports 1 = ",sports[0]);
  print("Sports 2 = ",sports[1]);
  print("Sports 3 = ",sports[2]);
  
# Call the details() function
demo("Football", "Hockey", "Cricket")
 

The output is as follows:

 
Sports 1 = Football
Sports 2 = Hockey
Sports 3 = Cricket
 

We passed *sports as variable-length/arbitrary argument above.

Let us see another example, wherein we will use for loop to display all the variable length argument
values:

  
#!/usr/bin/python
 
# Defining a Function with variable number of arguments
def demo(*sports):
  print("Displaying passed arguments...");
https://studyopedia.com/python3/functions-in-python/ 10/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia
p ( p y g p g );

  for name in sports:    


    print(name)    
 
# Call the details() function
demo("Football", "Hockey", "Cricket", "Squash", "Volleyball")
 

The output is as follows:

 
Displaying passed arguments...
Football
Hockey
Cricket
Squash
Volleyball
 

Arbitrary Keyword Arguments in Python (**kwargs)


Add two asterisks ** before the parameter name in function definition, if you don’t know in advance how
many keyword arguments will be passed to your function. Dictionary format gets created for such
arguments i.e. a Dictionary of arguments

Let us see an example:

 
#!/usr/bin/python
 
## Defining a Function with multiple keyword arguments **kwargs
def demo(**stu):
  print("Student name: " + stu["student"])
  print("Student section: " + stu["section"]) 
 
#Call the demo function
demo(student = "Jack",section = "AD")
 

Th t ti
https://studyopedia.com/python3/functions-in-python/
f ll 11/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia
The output is as follows:

 
Student name: Jack
Student section: AD
 

Recursion in Python
When a function calls itself, it is called Recursion.  In other sense, with Recursion, a defined function can
call itself. Recursion is a programming approach, which makes code efficient and reduces LOC. Let us
see an example wherein we will be calculating factorial with Recursion:

 
#function to calculate factorial
def calc(num):
    
    # Condition for 1! (1 factorial)
    if num == 0:
        return 1
    else:
        return num * calc(num-1)
        
#function call
print("0! = ",calc(0));
print("1! = ",calc(1));
print("7! = ",calc(7));
print("10! = ",calc(10));
 

The output is as follows:

 
0! = 1
1! = 1 
7! = 5040
10! = 3628800
 

The above program calls in a recursive way. To get the value of 7!, the function calc() works like:
https://studyopedia.com/python3/functions-in-python/ 12/17
3/5/22, 10:59 AM
p g yFunctions
g in Python with Examples -,Studyopedia ()

The return statement in Python


The return statement in Python is used to terminate/exit the function and is placed at the end. It can have
an expression or can be used without any expression. A return statement with an expression, gets
evaluated first and then returned to the function called. However, return statement with no expression
returns None. Let us now see an example:

  
#!/usr/bin/python
 
# Defining a Function
def demo(num):
  return 10 + num
https://studyopedia.com/python3/functions-in-python/ 13/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia
 
print(demo(2));
print(demo(10))
 

The output is as follows:

 
12
20
 

Let us see another example:

 
#!/usr/bin/python
 
# Defining a function
def demo( a, b, c ):
 
   res = a + b + c
   return res;
  
# Displaying result of sum
res = demo( 5, 7, 15);
print ("Result = ", res )
 
res = demo(50, 500, 1000);
print ("Result = ", res )
 

The output is as follows:

 
Result = 27
Result = 1550
 

Let us now see the above Python program without using return statement, since using return is optional: 

 
#!/usr/bin/python

https://studyopedia.com/python3/functions-in-python/ 14/17
3/5/22, 10:59 AM Functions in Python with Examples - Studyopedia
 
# Defining a function
def demo( a, b, c ):
   print ("Result = ", a+b+c)
 
# Displaying result of sum
demo( 5, 7, 15)
demo( 50, 500, 1000)
 

The output is as follows:

 
Result = 27
Result = 1550
 

In this lesson, we learned Functions in Python with several examples.We also saw how to work with
function arguments, including default, required, keyword, arbitrary arguments, etc.

Read More

Scope of Variables
Python Operators
Python Numbers
Type Conversion
Python Strings
Loops in Python
Decision Making Statements
Python Tuples
Python Dictionary 
Python Lists
Python DateTime

https://studyopedia.com/python3/functions-in-python/ 15/17

You might also like