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

Function Parameters

python functions

Uploaded by

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

Function Parameters

python functions

Uploaded by

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

Python User defined functions

A function is a set of statements that take inputs, do some specific computation, and produce output. The
idea is to put some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can call the function. Functions that readily
come with Python are called built-in functions. Python provides built-in functions like print(), etc. but we can
also create your own functions. These functions are known as user defines functions.

Table of Content
 User defined functions
 Parameterized functions

o Default arguments
o Keyword arguments
o Variable length arguments
o Pass by Reference or pass by value?

 Function with return value

Python User-defined functions


All the functions that are written by any of us come under the category of user-defined functions. Below are
the steps for writing user-defined functions in Python.
 In Python, a def keyword is used to declare user-defined functions.
 An indented block of statements follows the function name and arguments which contains the body of the
function.

Syntax:
def function_name():
statements
.
.

Example: Here we have created the fun function and then called the fun() function to print the statement.
Python
# Declaring a function
def fun():
print("Inside function")

# Driver's code
# Calling function
fun()

Output:
Inside function

Python Parameterized Function


The function may take arguments(s) also called parameters as input within the opening and closing
parentheses, just after the function name followed by a colon.
Syntax:
def function_name(argument1, argument2, ...):
statements
.
.

Example:
A simple Python function to check whether x is even or odd.
Python
def evenOdd( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd

Python Default arguments


A default argument is a parameter that assumes a default value if a value is not provided in the function call
for that argument. The following example illustrates Default arguments.
Example: We call myFun() with the only argument.
Python
# Python program to demonstrate
# default arguments
def myFun(x, y = 50):
print("x: ", x)
print("y: ", y)

# Driver code
myFun(10)
Output:
x: 10
y: 50

Python Keyword arguments


The idea is to allow the caller to specify the argument name with values so that the caller does not need to
remember the order of parameters.
Example: Python program to demonstrate Keyword Arguments
Python
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname ='Geeks', lastname ='Practice')
student(lastname ='Practice', firstname ='Geeks')
Output:
Geeks Practice
Geeks Practice

Global keyword in Python


What is the purpose of global keywords in python?
A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to
create global variables in Python from a non-global scope, i.e. inside a function. Global keyword is used
inside a function only when we want to do assignments or when we want to change a variable. Global is not
needed for printing and accessing.
Rules of global keyword:
 If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless
explicitly declared as global.
 Variables that are only referenced inside a function are implicitly global.
 We use a global keyword to use a global variable inside a function.
 There is no need to use global keywords outside a function.

Global keyword in the python example


Example 1: Accessing global Variable From Inside a Function

# global variable
a = 15
b = 10

# function to perform addition


def add():
c = a + b
print(c)

# calling a function
add()

Output:
25

Example 2: Modifying Global Variable From Inside the Function


 Python3
a = 15
# function to change a global value
def change():
# increment value of a by 5
b =a +5
a =b
print(a)
change()

Output:
UnboundLocalError: local variable 'a' referenced before assignment
This output is an error because we are trying to assign a value to a variable in an outer scope. This can be
done with the use of a global variable.

Example 3: Changing Global Variable From Inside a Function using global


 Python3
x = 15
def change():
# using a global keyword
global x
# increment value of a by 5
x =x +5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)

Output:
Value of x inside a function : 20
Value of x outside a function : 20

Example 1: Modifying list elements without using global keyword.

arr = [10, 20, 30]


def fun():
for i in range(len(arr)):
arr[i] += 10
print("'arr' list before executing fun():", arr)
fun()
print("'arr' list after executing fun():", arr)

Output:
'arr' list before executing fun(): [10, 20, 30]
'arr' list after executing fun(): [20, 30, 40]

Example 2: Modifying list variable using global keyword.

Here we are trying to assign a new list to the global variable. Thus, we need to use the global keyword as a
new object is created. Here, if we don’t use the global keyword, then a new local variable arr will be created
with the new list elements. But the global variable arr will be unchanged.
 Python3
arr = [10, 20, 30]
def fun():
global arr
arr = [20, 30, 40]
print("'arr' list before executing fun():", arr)
fun()
print("'arr' list after executing fun():", arr)

Output:
'arr' list before executing fun(): [10, 20, 30]
'arr' list after executing fun(): [20, 30, 40]
Python Scope of Variables
Python Scope variable
The location where we can find a variable and also access it if required is called the scope of a variable.
def f():

# local variable
s = "I love Geeksforgeeks"
print(s)

# Driver code
f()

Output
I love Geeksforgeeks
If we will try to use this local variable outside the function then let’s see what will happen.

def f():

# local variable
s = "I love Geeksforgeeks"
print("Inside Function:", s)

# Driver code
f()
print(s)

Output:
NameError: name 's' is not defined

Python Global variables

Global variables are the ones that are defined and declared outside any function and are not specified to any
function. They can be used by any part of the program.
Example:
 Python3
# This function uses global variable s
def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()

Output:
I love Geeksforgeeks

Global and Local Variables with the Same Name


Now suppose a variable with the same name is defined inside the scope of the function as well then it will
print the value given inside the function only and not the global value.
 Python3

# This function has a variable with


# name same as s.
def f():
s = "Me too."
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()
print(s)

Output:
Me too.
I love Geeksforgeeks
Consider the below example for a better understanding of the topic.
 Python3

# Python program to demonstrate


# scope of variable

a =1

# Uses global because there is no local 'a'


def f():
print('Inside f() : ', a)

# Variable 'a' is redefined as a local


def g():
a =2
print('Inside g() : ', a)

# Uses global keyword to modify global 'a'


def h():
global a
a =3
print('Inside h() : ', a)

# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)

Output:
global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3

How to pass optional parameters to a function in Python?


In Python, when we define functions with default values for certain parameters, it is said to have its
arguments set as an option for the user. Users can either pass their values or can pretend the function to use
theirs default values which are specified.
In this way, the user can call the function by either passing those optional parameters or just passing the
required parameters.
There are two main ways to pass optional parameters in python
 Without using keyword arguments.
 By using keyword arguments.
Passing without using keyword arguments
Some main point to be taken care while passing without using keyword arguments is :
 The order of parameters should be maintained i.e. the order in which parameters are defined in function
should be maintained while calling the function.
 The values for the non-optional parameters should be passed otherwise it will throw an error.
 The value of the default arguments can be either passed or ignored.
Below are some codes which explain this concept.

Example 1:
Python
# Here b is predefined and hence is optional.
def func(a, b=1098):
return a+b
print(func(2, 2))

# this 1 is represented as 'a' in the function and


# function uses the default value of b
print(func(1))

Output:
4
1099
Example 2: we can also pass strings.
Python
# Here string2 is the default string used
def fun2(string1, string2="Geeks"):
print(string1 + string2)

# calling the function using default value


fun2('GeeksFor')

# calling without default value.


fun2('GeeksFor', "Geeks")

Output:
GeeksForGeeks
GeeksForGeeks
Passing with keyword arguments
When functions are defined then the parameters are written in the form “datatype keyword-name”. So python
provides a mechanism to call the function using the keyword name for passing the values. This helps the
programmer by relieving them not to learn the sequence or the order in which the parameters are to be
passed.
Some important points we need to remember are as follows:
 In this case, we are not required to maintain the order of passing the values.
 There should be no difference between the passed and declared keyword names.

Below is the code for its implementation.


Python
# Here string2 is the default string used
def fun2(string1, string2="Geeks"):
print(string1 + string2)

# Thiscan be a way where no order is needed.


fun2(string2='GeeksFor', string1="Geeks")

# since we are not mentioning the non-default argument


# so it will give error.
fun2(string2='GeeksFor')

Output:

As we can see that we don’t require any order to be maintained in the above example. Also, we can see that
when we try to pass only the optional parameters then it raises an error. This happens since optional
parameters can be omitted as they have a default with them, but we cannot omit required parameters (string1
in the above case.) Hence, it shows an error with the flag: “missing 1 required argument”.

This example will give a more insight idea of above topic:


Python
def func(a, b, c='geeks'):
print(a, "type is", type(a))
print(b, "type is", type(b))
print(c, "type is", type(c))

# The optional parameters will not decide


# the type of parameter passed.
# also the order is maintained
print("first call")
func(2, 'z', 2.0)

# below call uses the default


# mentioned value of c
print("second call")
func(2, 1)

# The below call (in comments) will give an error


# since other required parameter is not passed.
# func('a')
print("third call")
func(c=2, b=3, a='geeks')
Output:
first call
2 type is <class 'int'>
z type is <class 'str'>
2.0 type is <class 'float'>
second call
2 type is <class 'int'>
1 type is <class 'int'>
geeks type is <class 'str'>
third call
geeks type is <class 'str'>
3 type is <class 'int'>
2 type is <class 'int'>
So basically python functional calls checks only if the required number of functional parameters are passed or
not.
Below shows the case where a user tries to pass arguments in both ways discussed above along with
the precaution given:
Python
def comp(a, b=2):
if(a < b):
print("first parameter is smaller")
if(a > b):
print("second parameter is smaller")
if(a == b):
print("both are of equal value.")

print("first call")
comp(1)
print("second call")
comp(2, 1)
print("third call")
comp(b=1, a=-1)
print("fourth call")
comp(-1, b=0)

Output:
first call
first parameter is smaller
second call
second parameter is smaller
third call
first parameter is smaller
fourth call
first parameter is smaller

So one thing we should remember that the keyword argument should used after all positional arguments are
passed. Hence this is an important thing we must keep in mind while passing parameters in both ways to
same function.
How to pass optional parameters to a function in Python? – FAQs

How to pass optional parameters in Python function?


To pass optional parameters in a Python function, you can define default values for parameters in the function
definition. This allows the function to be called with fewer arguments than defined.

How to give an optional parameter to a function?


An optional parameter is given to a function by assigning it a default value in the function definition. For
example:
def example_function(param1, optional_param=None):
# Function body
In this case, optional_param is optional and defaults to None if not provided.
How to pass extra arguments to a function in Python?
You can pass extra arguments to a function using *args for positional arguments and **kwargs for keyword
arguments. This allows the function to accept an arbitrary number of additional arguments.

How to skip positional arguments in Python?


Skipping positional arguments in a function call can be achieved by using keyword arguments. This way, you
can specify only the arguments you want to pass, and the rest will use their default values.

def example_function(a, b=2, c=3):


# Function body

example_function(a=1, c=4) # b uses its default value of 2


What does args mean in Python?
*args in a function definition allows the function to accept a variable number of positional arguments. Inside
the function, args is a tuple containing all the positional arguments passed. It is used when you want to create
functions that can handle an arbitrary number of positional arguments

You might also like