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

Functions in PYTHON Handout

Functions in Python allow for modular and reusable code. A function is defined using the def keyword and can take in parameters. Functions can return values and have local and global scopes. Parameters are formal arguments, while arguments are the actual values passed during a function call.

Uploaded by

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

Functions in PYTHON Handout

Functions in Python allow for modular and reusable code. A function is defined using the def keyword and can take in parameters. Functions can return values and have local and global scopes. Parameters are formal arguments, while arguments are the actual values passed during a function call.

Uploaded by

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

Functions in PYTHON

A function is a block of organized, reusable code that is used to perform a single,


related predefined action. Functions provide better modularity and reusability of code
in programs.
Python not only offers many built-in functions like print(), etc. but also allows a
programmer to write their own functions. These functions are called user-defined
functions.

Defining a Function
You can define functions to provide the required syntax to be written in a program.
Syntax:

● The first line of the function definition is called the function header; the rest is
called the body. The function is declared with the keyword def. The function
header has to end with a colon (:) and the body has to be indented.
● The function_name must be a user-defined name or an identifier or variable
name.
● The formal_parameters or arguments are optional. Parameters are specified
within the pair of parentheses in the function definition, separated by commas.
● The body of the function consists of one or more Python statements with at
least — 4 spaces indentation.
● The return statement is optional. If you want to return a value(s) to the calling
statement, then use return with the value/values separated by commas.
● To end the function body, you have to enter an empty line in interactive mode
but this is not necessary in script mode.

Parameters:
● Parameters are the value(s) provided in the parenthesis when we write a
function header. These are the values required by the function to work.
● If there are more than one parameters, they must be separated by commas(,)
● An Argument is a value that is passed to the function when it is called. In other
words, arguments are the value(s) provided in function call/invoke statement
● Parameters are also known as FORMAL ARGUMENTS/PARAMETERS
● Arguments are also known as ACTUAL ARGUMENTS/PARAMETERS
● By default, parameters have a positional behavior and you need to pass them to
the function in the same order that they were defined in the function header.
Example:
Here is the simplest form of a Python function. This function takes a string as input
parameter and prints it on the standard screen.
def printme( str ):
#‘This prints a passed string into this function’
print(str)
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.

Python just executes the function header line to determine that it is correct and
skips all lines in the function body. These statements are not executed until the
function is called.

Following is the example to define and call printme() function:


# Function definition is here
def printme( str ):
#"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("I’m first call to user defined function!");
printme("Again second call to the same function");

When the above code is executed, it produces the following result:


I'm first call to user defined function!
Again second call to the same function

Function Arguments:
You can call a function by using the following types of formal arguments:
1. Positional/Required arguments
2. Keyword arguments
3. Default arguments
4. Variable Length Parameters

Positional/Required arguments:
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with
the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
would give a syntax error as follows:
# Function definition is here
def printme(str):
#"This prints a passed string into this function"
print(str)
return
# Now you can call printme function
printme()

When the above code is executed, it produces the following result:


Traceback (most recent call last):
File "test.py", line 11, in <module>;
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments:
Keyword arguments specify the argument name alongwith the argument value in a
function call. When you use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways:
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result:
My string

Following example gives a clearer picture. Note, here the order of the parameters does
not matter.
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print( "Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result:
Name: miki
Age 50

Default arguments:
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. Following example gives an idea on
default arguments; it would print default age if it is not passed:
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print( "Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result:
Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments:
Sometimes we may not know the number of arguments to be passed in advance. In
such cases, Python provides us the flexibility to offer the comma-separated values
which are internally treated as tuples at the function call. By using the variable-length
arguments, we can pass any number of arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple):
function_body
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all non-
keyword variable arguments. This tuple remains empty if no additional arguments are
specified during the function call. Following is a simple example −
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print(arg1)
for var in vartuple:
print(var)
return

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50

The return Statement:


 A function that returns a value is called a fruitful function.
 The opposite of a fruitful function is a void function. The return keyword is
used to return values from a function.
 A function may or may not return a value.
 If a function does not have a return keyword, it will send a None value, i.e.,
equivalent to return None. None is a special type in Python that represents
nothingness (no value). For example, it is used to indicate that a variable has no
value if it has a value of None.
All the above examples are not returning any value, but if you like you can return a
value from a function as follows:
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function: ", total)
return total

# Now you can call sum function


total = sum( 10, 20 );
print ("Outside the function: ", total)

When the above code is executed, it produces the following result:


Inside the function: 30
Outside the function: 30

Scope of Variables:
All variables in a program may not be accessible at all places in the program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python:
 Global variables
 Local variables

Global vs. Local variables:


 Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
 Local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program
body by all functions.
 When you call a function, the variables declared inside it are brought into scope.

Following is a simple example:


total = 0 # This is a global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them
total = arg1 + arg2 # Here the total is a local variable.
Print (“Inside the function local total : “, total)
return total

# Now you can call sum function


sum( 10, 20 );
print “Outside the function global total : “, total

When the above code is executed, it produces the following result:


Inside the function local total: 30
Outside the function global total: 0

Use of global keyword:


Although global variables can be accessed freely from all parts of a program, they
cannot be modified inside any function if they are immutable in nature. So, if you want
to modify a global variable in a function just add the following statement,
global <varname> before changing its value.
In Python, global keyword allows you to modify the variable outside of the current
scope. It is used to create a global variable and make changes to the variable in a local
context.

total = 0 # This is a global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them.
global total
total = arg1 + arg2 # Here the total is the global variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum()
sum( 10, 20 )
print("Outside the function global total : ", total)

Now, when the above code is executed, it produces the following result:
Inside the function total: 30
Outside the function global total: 30

You might also like