test1 (5)
test1 (5)
2 Function Call
Defining a function gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt.
#!/usr/bin/python3
print (str)
return
All variables in a program may not be accessible at all locations in that 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
1
Local variables
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope This means that 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.
#!/usr/bin/python3
return total
sum( 10, 20 )
The return statement is used to exit a function and go back to the place from where it
was called. This statement can contain expression which gets evaluated and the value is
returned.
2
If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
def hf():
return "hw"
print(hf())
Output:
You can call a function by using the following types of formal arguments-
Required arguments
Keyword arguments
Default arguments
Variable-length 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
gives a syntax error as follows-
#!/usr/bin/python3
print (str)
return
3.2.2. Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
You can also make keyword calls to the printme() function in the following ways-
#!/usr/bin/python3
print (str)
return
#!/usr/bin/python3
return
printinfo( name="miki" )
Name: miki
Variable-length Arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default arguments.
function_suite
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments are
specified during the function call. Following is a simple example-
#!/usr/bin/python3
print (arg1)
print (var)
return
printinfo( 10 )
3.2.4 Recursion
6
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number.
For example,
def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial",fact(0))
print("five factorial",fact(5)
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or double
quotes. Every string object is of the type „str‟.
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
>>> a=str('mrcet')
>>> a
'mrcet'
> letter = fruit[1] The second statement selects character number 1 from fruit and
assigns it to letter. The expression in brackets is called an index. The index indicates which
character in the sequence we want.
8
3.3.1 String Operations
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example String operators
represent the different types of operations that can be employed on the program’s string type
of variables. Python allows several string operators that can be applied on the python string
are as below:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
9
Two strings can be concatenated or join using the “+” operator in python, as
explained in the below example code:
string1 = "hello"
string_combined = string1+string2
print(string_combined)
output
The same string can be repeated in python by n times using string*n, as explained in
the below example.
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
output
helloworld helloworld
10
3.3.2 Immutable Strings
In python, the string data types are immutable. Which means a string value cannot be
updated. We can verify this by trying to update a part of the string which will led us to an
error.
t= "Tutorialspoint"
print type(t)
t[0] = "M"
Note: All the string methods will be returning either true or false as the result
11
1. isalnum():
Isalnum() method returns true if string has at least 1 character and all characters are
Syntax:
String.isalnum()
Example:
>>> string="123alpha"
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
12
Syntax:
String.isalpha()
Example:
>>> string="nikhil"
>>> string.isalpha()
True
3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
String.isdigit()
Example:
>>> string="123456789"
>>> string.isdigit()
True
4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise.
Syntax:
String.islower()
Example:
>>> string="nikhil"
>>> string.islower()
True
13
5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
Syntax:
String.isnumeric()
Example:
>>> string="123456789"
>>> string.isnumeric()
True
6. isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.
Syntax:
String.isspace()
Example:
>>> string.isspace()
True
7. istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise
Syntax:
14
String.istitle()
Example:
>>> string.istitle()
True
8. isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.
Syntax:
String.istitle()
Example:
>>> string="HELLO"
>>> string.isupper()
True
9. replace()
replace() method replaces all occurrences of old in string with new or at most max
Syntax:
String.istitle()
String.replace()
Example:
>>> string.replace('Nikhil','Neha')
15
'Neha Is Learning'
10.split()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
String.split()
Example:
>>> string.split()
11.count()
Syntax:
String.count()
Example:
>>> string.count('i')
12.find()
Find() method is used for finding the index of the first occurrence of a string in another
string.
Syntax:
16
String.find(„string‟)
Example:
>>> string.find('k')
13.swapcase()
Syntax:
String.find(„string‟)
Example:
>>> string="HELLO"
>>> string.swapcase()
'hello'
14.startswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
Syntax:
String.startswith(„string‟)
Example:
>>> string.startswith('N')
True
17
15.endswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with substring str; returns true if so and false otherwise.
Syntax:
String.endswith(„string‟)
Example:
>>> string.startswith('g')
True
The == operator compares the values of both the operands and checks for value
equality. Whereas is operator checks whether both the operands refer to the same object or
not. The same is the case for != and is not.
Code:
str1 = "Geek"
str2 = "Geek"
str3 = str1
print(str1 is str1)
print(str1 is str2)
18
print(str1 is str3)
str1 += "s"
3.4 Modules
A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file
namedaname.py.
return
19
3.4.1 Import Statement
You can use any Python source file as a module by executing an import statement in
some other Python source file. The import has the following syntax
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the interpreter
searches before importing a module. For example, to import the module hello.py, you need to
put the following command at the top of the script-
#!/usr/bin/python3
import support
support.print_func("Zara")
20
We use modules to break down large programs into small manageable and organized
files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying
their definitions into different programs.
Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or modules.
Advantages:
Simplicity:
Rather than focusing on the entire problem at hand, a module typically focuses on one
relatively small portion of the problem.
If you‟re working on a single module, you‟ll have a smaller problem domain to wrap
your head around. This makes development easier and less error-prone.
Maintainability:
Modules are typically designed so that they enforce logical boundaries between different
problem domains. If modules are written in a way that minimizes interdependency, there is
decreased likelihood that modifications to a single module will have an impact on other parts
of the program.
This makes it more viable for a team of many programmers to work collaboratively
on a large application.
Reusability: Functionality defined in a single module can be easily reused (through an
appropriately defined interface) by other parts of the application. This eliminates the
need to recreate duplicate code.
Scoping: Modules typically define a separate namespace, which helps avoid collisions
between identifiers in different areas of a program.
Functions, modules and packages are all constructs in Python that promote code
modularization.
A file containing Python code, for e.g.: example.py, is called a module and its module
name would be example.
result=a+b
21
return result
>>> dir(example)
[' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' spec ', 'add']
>>> dir()
[' annotations ', ' builtins ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' spec ', ' warning
registry ', 'add', 'example', 'hi', 'imp']
For ex
'example'
A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file
namedaname.py.
return
Namespaces
22
variable names (keys) and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes
that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.
The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function
Money, we assign Money a value, therefore Python assumes Money as a local variable.
However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python3
Money = 2000
def AddMoney():
# global Money
Money = Money + 1
print (Money)
AddMoney()
23
3.4.5 Defining our own modules
You can use any Python source file as a module by executing an import statement in
some other Python source file.
The import has the following syntaximport module1[, module2[,... moduleN] When the
interpreter encounters an import statement, it imports the module if the module is present in
the search path.
A search path is a list of directories that the interpreter searches before importing a
module. For example, to import the module hello.py, you need to put the following command
at the top of the script-
#!/usr/bin/python3
import support
support.print_func("Zara")
Hello : Zara
24
Unit – IV
4. Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists are
similar to arrays in C. One of the differences between them is that all the items belonging to a
list can be of different data type.
Create a List:
print(thislist)
List Items
List items are indexed and you can access them by referring to the index number:
Example
print(thislist[1])
25
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
Example
print(thislist[-1])
Example
thislist[1] = "blackcurrant"
print(thislist)
To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
print(thislist)
26
If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
print(thislist)
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the
insert() method.
Example
thislist.insert(2, "watermelon")
print(thislist)
A nested list in python allows a list to contain multiple sublists within itself. Each
sublist can have items of different data types. It can be created by placing comma-separated
sublists and items together. Following is an example of a nested list in python satisfying the
above-mentioned criteria.
27
Example
ecommerce=[['books',['comedy','horror'],'toys','kitchenware'],
[200,100,350]]
Output:
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
Repetition
Concatenation
Length
Iteration
Membership
1. Repetition
The repetition operator enables the list elements to be repeated multiple times.
Code:
# repetition of list
# repetition operator *
l = list1 * 2 28
print(l)
Output:
2. Concatenation
Code:
29