Unit III - Functions
Definition: Python Functions is a block of statements that return the specific task. 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 do the
function calls to reuse code contained in it. A function only runs when it is called. We can
pass data, known as parameters, into a function. A function can return data as a result.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Types of Functions in Python
Below are the different types of functions in Python:
Built-in library function: These are Standard functions in Python that are available
to use.
User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require.
Syntax
def function_name( parameters ):
# code block
# Example - A simple Python function
def fun():
print("Welcome to Python")
Working of a function
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function.
# A simple Python function
def fun():
print("Welcome to python")
# Code to call a function
fun()
output: Welcome to python
Variable scope and its Lifetime
Scope
A variable is only available from inside the region it is created. This is called scope. The
location where we can find a variable and also access it if required is called the scope of a
variable.
Python Local variable
Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.
A variable created inside a function is available inside that function:
Example
def myfunc():
x = 300
print(x)
myfunc()
Output:300
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the
global scope.
Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
example
x = 300
def myfunc():
print(x)
myfunc()
x=x+100
print(x)
Output:
300
400
Python return statement
A return statement is used to end the execution of the function call and “returns” the
result (value of the expression following the return keyword) to the caller. The statements
after the return statements are not executed. If the return statement is without any
expression, then the special value None is returned. A return statement is overall used to
invoke a function so that the passed statements can be executed.
Note: Return statement can not be used outside the function.
Syntax:
def fun():
statements
.
.
return [expression]
example:
def myfunction():
return 3+3
print(myfunction())
Function Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. We can add as many
arguments as you want, just separate them with a comma.
Parameter Vs Argument
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
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.
Example (with error)
To call the function printme(), we definitely need to pass one argument, otherwise it gives a
syntax error as follows –
[Link]
---
---
# Function definition is here
def printme( str ):
#"This prints a passed string into this function"
print(str)
return
# Now you can call printme function in main
printme()
Output
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "[Link]", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Example (with correct output)
def my_function(fname,lname):
print(fname+lname)
my_function("Arun ",”Kumar”)
output: Arun Kumar
Variable length arguments
If we do not know how many arguments that will be passed into our function, add a * before
the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly.
There are two types of variable length arguments in python. They are:
Non – Keyworded Arguments (*args)
Keyworded Arguments (**kwargs)
Python *args
Arbitrary Arguments are often shortened to *args in Python [Link]
Python, *args is used to pass a variable number of arguments to a function. It is used to
pass a variable-length, non-keyworded argument list. These arguments are collected into a
tuple within the function and allow us to work with them.
Example
def my_function(*subject):
print(“My favourite studies is : “+subject[2])
my_function(“Tamil”,”English”,”python”)
Output: My favourite studies is: python
Python **kargs
In Python, **kwargs is used to pass a keyworded, variable-length argument list.
Here we can send args with the key=value syntax. Arguments are collected into a
dictionary within the function that allow us to access them by their keys. The order of
the arguments does not matter.
Example
def display_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
display_info(name="Alice", age=30, city="New York")
Output:
name: Alice
age: 30
city: New York
Default arguments
If we call the function without argument, it uses the default value.
The following example shows how to use a default parameter value.
Example
def my_function(country = "India"):
print("I am from " + country)
my_function("Japan")
my_function("Sweden")
my_function()
my_function("Brazil")
Output:
I am from Japan
I am from Sweden
I am from India
I am from Brazil
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself.
Need to recurse a function
When we want to perform a complex task, we generally break it into smaller tasks;
doing them one after the other decreases the burden and the complexity.
Just like this, when we need to write a code for a complex problem, we break it into
smaller and repetitive parts.
Syntax:
def function_name(arguments if any):
#function body
function_name(argument) #recursive call of the function
example
example
def func(): <--
|
| (recursive call)
|
func() ----
Example: Finding factorial value of a given number using recursion.
Python strings
A String in Python Programming represents a sequence of characters. It is an immutable
data type, meaning that once we have created a string, we cannot change it. It is used
widely in many different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
#You can use double or single quotes:
print("Hello")
print('Hello')
Output:
Hello
Hello
Quotes Inside Quotes
We can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Output:
It’s alright
He is called ‘Johnny’
He is called “Johnny”
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:
Example
a = "Anjac"
print(a)
Output
Anjac
Multiline Strings
We can assign a multiline string to a variable by using three quotes:
We can use three double quotes:
Example
a = """This is first line,
This is second line,
This is third line."""
print(a)
output:
This is first line,
This is second line,
This is third line.
Strings are Arrays
Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
output: e
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with
a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
output:
b
a
n
a
n
a
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello,World!"
print(len(a))
Output: 12
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "father" is present in the following text:
txt = "Charles Babbage is known as the father of computers"
print("father" in txt)
output: True
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are moral based"
print("expensive" not in txt)
Output: False
String operations
Python String Operators
Operator Description
+ It is known as concatenation operator used to join the strings.
* It is known as repetition operator. It concatenates the multiple copies of the same
string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
in It is known as membership operator. It returns if a particular sub-string is present in
the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r / R It is used to specify the raw string. To define any string as a raw string, the character r or R is
followed by the string.
% It is used to perform string formatting. It makes use of the format specifies used in C
programming like %d or %f to map their values in python.
Immutable strings
Strings in Python are “immutable” which means they can not be changed after they are
created. Immutability refers to the property of an object, that we can not change the object
after we declare it.
-
-
my_string = "GeekGeek"
# Attempt to modify the string
my_string[0] = 'for' # Raises TypeError
Output (error)
Hangup (SIGHUP)
Traceback (most recent call last):
File "[Link]", line 4, in <module>
my_string[0] = 'for' # Raises TypeError: 'str' object does not support item assignment
TypeError: 'str' object does not support item assignment
Built-in string methods and functions
- Refer note -
String comparison
String comparison is a fundamental operation in python. The relational operators are the
Unicode values of the characters of the strings from the zeroth index till the end of the
string. It then returns a boolean value according to the operator used.
#example program for string comprison
def compare_String(str1,str2):
if str1<str2:
return -1 #string1 is alphabetically above than string2
elif str1>str2:
return 1 #string1 is alphabetically below than string2
else:
return 0 #strings are equal
print(compare_String("hello","hello"))
print(compare_String("hello","world"))
print(compare_String("world","hello"))
Output:
0
-1
1
Modules
A python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables. A module can also include runnable code. A
module can be reused in multiple python files.
Uses:
[Link] related code into a module makes the code easier to understand and use.
[Link] also makes the code logically organized that is structuring code effectively.
[Link] helps to reuse the code.
Module combines the following 2 operations:
1. Import module searches for the named module.
2. Then it binds the results of that search to a name in the local scope.
Import statement
(i)from keyword:
from math import pi
print (pi)
Output: 3.141592653589793
(ii)alias name usage
Import math as m
res=[Link](25)
print(res)
Output: 5
(iii) usage of *
from math import *
print(pi)
3.141592653589793
print(factorial(6))
720
The python module – defining our own modules.
Apart from the built-in modules, user can create their own module. To import the module and
used in the calling program, the following syntax is used(for user defined module).
Modulefile_name.function_name_in_module
Example:
my_module.py
def greeting(x):
print(“Hello”,x)
[Link]
import my_module
my_module.greeting(“Tech”)
output: Hello Tech
Dir() function
In Python, the dir() function is a built-in function used to list the attributes (methods,
properties, and other members) of an object.
Syntax: dir({object})
Eg.
Print(dir())
[‘_annotations_’, ‘_builtins_’,..]
Print(dir(math))
[‘_doc_’, ‘sin’, ‘sqrt’, ‘tan’, ‘trunc’ ...]
Modules and Namespace
In Python, a module namespace is a namespace that contains all the symbols that are
defined in a module. When we import a module, all the symbols in the module’s namespace
are made available to the caller, but they are put into the module’s namespace, rather than the
caller’s. This helps to prevent the caller from accidentally overwriting symbols that are
defined in the module.
my_module.py
# define a function in the module namespace
def func():
print("I am a function in the module namespace")
# define a variable in the module namespace
x = 10
[Link]
import my_module
# access the function and variable in the module namespace
my_module.func() # prints "I am a function in the module namespace"
print(my_module.x) # prints 10
output:
I am a function in the module namespace
10
Types of namespace:
There are 4 types of namespace. They are as follows.
1. Built-in namespace: This namespace contains objects that are built into python such
as built-in functions. Eg. Abs function
2. Enclosing namespace: It corresponds to the namespace of enclosing functions (for
nested functions).
3. Global namespace: It contains any names defined at the levels of the main program.
4. Local namespace: It is used by the function.
eg.
#global namespace – var1
var1=5
def func1():
#local namespace – var2
var2=6
def func2():
#enclosed namespace - nested – var3
var3=7
Unit – IV Lists and Dictionaries
The list is a sequence data type which is used to store the collection of data. Lists are used
to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set and Dictionary.
List items:
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered:
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable:
The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.
Allow Duplicates:
Since lists are indexed, lists can have items with the same value:
Creating a List
list=[1,2,5,8,10]
print(list)
output: [1,2,5,8,10]
Accessing values in a list
To access the list,
print(list[0])
print(list[2])
Output:
1
5