0% found this document useful (0 votes)
18 views

test1 (5)

The document provides an overview of Python functions, including their definition, calling methods, variable scope, and the return statement. It discusses different types of function arguments such as required, keyword, default, and variable-length arguments, as well as recursion. Additionally, it covers string operations, immutability, built-in string methods, and the concept of modules in Python programming.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

test1 (5)

The document provides an overview of Python functions, including their definition, calling methods, variable scope, and the return statement. It discusses different types of function arguments such as required, keyword, default, and variable-length arguments, as well as recursion. Additionally, it covers string operations, immutability, built-in string methods, and the concept of modules in Python programming.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

3.1.

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.

Following is an example to call the printme() function-

#!/usr/bin/python3

# 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("This is first call to the user defined function!")

printme("Again second call to the same function")

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

3.1.3 Variable Scope and its Lifetime

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

Global vs. 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.

Following is a simple example:

#!/usr/bin/python3

total = 0 # This is global variable.

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2; # Here total is 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

3.1.4 Return Statement

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:

3.2 Function Arguments

You can call a function by using the following types of formal arguments-

 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

3.2.1 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
gives a syntax error as follows-

#!/usr/bin/python3

# Function definition is here

def printme( str ):

"This prints a passed string into3 this function"

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

# 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( str = "My string")

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


4
3.2.3 Default Arguments and Variable Length 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. The following example gives an idea on
default arguments, it prints default age if it is not passed.

#!/usr/bin/python3

# Function definition is here

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

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.

Syntax for a function with non-keyword variable arguments is given below

def functionname([formal_args,] *var_args_tuple ):


5
"function_docstring"

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

# Function definition is here

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

3.2.4 Recursion

Recursion is the process of defining something in terms of itself.

Python Recursive Function

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,

the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

Following is an example of recursive function to find the factorial of an integer.

# Write a program to factorial using recursion

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):

"""This is a recursive function

to find the factorial of an integer"""

if x == 1:

return 1

else:

return (x * calc_factorial(x-1))

num = 4

print("The factorial of", num, "is", calc_factorial(num))


7
3.3 Python strings

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:

 Assignment operator: “=.”


 Concatenate operator: “+.”
 String repetition operator: “*.”
 String slicing operator: “[]”
 String comparison operator: “==” & “!=”
 Membership operator: “in” & “not in”
 Escape sequence operator: “\.”
 String formatting operator: “%” & “{}”

Example #1 – Assignment Operator “=”

Python string can be assigned to any variable with an assignment operator “= “.


Python string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple
quotes[‘’’ ‘’’]. var_name = “string” assigns “string” to variable var_name.

string1 = "hello"

string2 = 'hello'

string3 = '''hello'''

print(string1)

print(string2)

print(string3)

Example #2 – Concatenate Operator “+”

9
Two strings can be concatenated or join using the “+” operator in python, as
explained in the below example code:

string1 = "hello"

string2 = "world "

string_combined = string1+string2

print(string_combined)

output

Example #3 – String Repetition Operator “*”

The same string can be repeated in python by n times using string*n, as explained in
the below example.

string1 = "helloworld "

print(string1*2)

print(string1*3)

print(string1*4)

print(string1*5)

output

helloworld helloworld

helloworld helloworld helloworld

helloworld helloworld 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.

# Can not reassign

t= "Tutorialspoint"

print type(t)

t[0] = "M"

When we run the above program, we get the following output –


t[0] = "M"

3.3.3 Built-in String methods and Functions

Python includes the following built-in methods to manipulate strings

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

alphanumeric and false otherwise.

Syntax:

String.isalnum()

Example:

>>> string="123alpha"

>>> string.isalnum() True

2. isalpha():

isalpha() method returns true if string has at least 1 character and all characters are

alphabetic and false otherwise.

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=" "

>>> 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="Nikhil Is Learning"

>>> 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

occurrences if max given.

Syntax:

String.istitle()

String.replace()

Example:

>>> string="Nikhil Is Learning"

>>> 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="Nikhil Is Learning"

>>> string.split()

['Nikhil', 'Is', 'Learning']

11.count()

count() method counts the occurrence of a string in another string.

Syntax:

String.count()

Example:

>>> string='Nikhil Is Learning'

>>> 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="Nikhil Is Learning"

>>> string.find('k')

13.swapcase()

converts lowercase letters in a string to uppercase and viceversa

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="Nikhil Is Learning"

>>> 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="Nikhil Is Learning"

>>> string.startswith('g')

True

3.3.4 String Comparison

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.

Let us understand this with an example:

Code:
str1 = "Geek"

str2 = "Geek"

str3 = str1

print("ID of str1 =", hex(id(str1)))

print("ID of str2 =", hex(id(str2)))

print("ID of str3 =", hex(id(str3)))

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.

Here is an example of a simple module, support.py

def print_func( par ):

print "Hello : ", par

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

import 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 module support

import support

# Now you can call defined function that module as follows

support.print_func("Zara")

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

3.4.2 The Python Module

Modules refer to a file containing Python statements and definitions.

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.

>>> def add(a,b):

result=a+b

21
return result

3.4.3 dir() Function

>>> import example

>>> 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']

It shows all built-in and user-defined modules.

For ex

>>> example. _____name_____

'example'

3.4.4 Modules and Namespace

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.

Here is an example of a simple module, support.pydef print_func( par ):

print "Hello : ", par

return
Namespaces

Variables are names (identifiers) that map to objects. A namespace is a dictionary of

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():

# Uncomment the following line to fix the code:

# global Money

Money = Money + 1

print (Money)

AddMoney()

23
3.4.5 Defining our own modules

The 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 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 module support

import support

# Now you can call defined function that module as follows

support.print_func("Zara")

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

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.

4.1 Creating a List

Lists are created using square brackets:

Create a List:

thislist = ["apple", "banana", "cherry"]

print(thislist)

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.

4.2 Access Values in List

List items are indexed and you can access them by referring to the index number:

Example

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]

print(thislist[1])
25
Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]

print(thislist[-1])

4.3 Updating Values in Lists

To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]

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":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]

thislist[1:3] = ["blackcurrant", "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

Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]

thislist[1:2] = ["blackcurrant", "watermelon"]

print(thislist)

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the
insert() method.

The insert() method inserts an item at the specified index:

Example

Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]

thislist.insert(2, "watermelon")

print(thislist)

4.4 Nested List

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]]

print(f"Displaying products offered by our website: {products}")

Output:

Displaying products offered by our website: [['books', ['comedy',


'horror'], 'toys', 'kitchenware'], [200, 100, 350]]

4.5 Basic List Operations

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

Let's see how the list responds to various operators.

1. Repetition

The repetition operator enables the list elements to be repeated multiple times.

Code:

# repetition of list

# declaring the list

list1 = [12, 14, 16, 18, 20]

# repetition operator *

l = list1 * 2 28
print(l)
Output:

2. Concatenation

It concatenates the list mentioned on either side of the operator.

Code:

29

You might also like