0% found this document useful (0 votes)
23 views83 pages

UNIT 1 PDS Notes

The document outlines a course on Python for Data Science, covering objectives such as problem-solving with Python, data structures, exploratory data analysis, and data visualization. It includes detailed units on control flow, functions, data science fundamentals, NumPy, Pandas, and Matplotlib. Additionally, it discusses Python's features, interpreter modes, debugging, and common errors in programming.

Uploaded by

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

UNIT 1 PDS Notes

The document outlines a course on Python for Data Science, covering objectives such as problem-solving with Python, data structures, exploratory data analysis, and data visualization. It includes detailed units on control flow, functions, data science fundamentals, NumPy, Pandas, and Matplotlib. Additionally, it discusses Python's features, interpreter modes, debugging, and common errors in programming.

Uploaded by

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

AD23211 PYTHON FOR DATA SCIENCE L T P C

3 0 0 3
COURSE OBJECTIVES:
 To learn to solve problems using Python conditionals and loops, functions, lists and
tuples to solve problems.
 To use Python data structures – Sets, dictionaries to represent complex data and also
input/output with files in Python.
 To outline an overview of exploratory data analysis.
 To implement arrays, Data frames and Datasets using NumPy and Pandas
 To implement data visualization using Matplotlib.

UNIT I CONTROL FLOW, FUNCTIONS, LISTS, TUPLES 9


Python interpreter – Data types – variables - expressions - Boolean values and operators -
Conditionals: conditional (if) - alternative (if-else) - chained conditional (if- elif-
else);Iteration: while - for - break - continue - pass; Fruitful functions: return values
- parameters - local and global scope - function composition - recursion; Strings - String
Operations - Lists as arrays. Lists: list operations - list slices - list methods - list loop -
mutability - aliasing - cloning lists - list parameters; Tuples: tuple assignment - tuple as
return value

UNIT II SETS, DICTIONARIES, FILES, PACKAGES 9


Sets – operations - methods; Dictionaries - operations and methods; advanced list processing
- list comprehension. Files and exceptions: text files - reading and writing files - format
operator; command line arguments - Errors and exceptions - handling exceptions - Modules -
Packages; Illustrative Programs.

UNIT III FUNDAMENTALS OF DATA SCIENCE 9


Need for data science – benefits and uses – facets of data – data science process – setting the
research goal – retrieving data – cleansing - integrating and transforming data -Exploratory
Data Analysis (EDA) fundamentals – Understanding data science – Significance of EDA –
Making sense of data –Software tools for EDA - Visual Aids for
EDA. Case Study: Health care - Retail - Banking-Fraud Detection.

UNIT IV NUMPY AND PANDAS 9


Understanding Data Types in Python -The Basics of NumPy Arrays - Computation on NumPy
Arrays: Universal Functions - Aggregations: Min, Max, and Everything In Between. Introducing
Pandas Objects - Data Indexing and Selection - Operating on Data in Pandas - Handling Missing
Data - Hierarchical Indexing - Combining Datasets: Concat and Append - Combining Datasets:
Merge and Join - Aggregation and Grouping - Pivot Tables - Vectorized String Operations -
Working with Time Series.

UNIT V VISUALIZATION WITH MATPLOTLIB 9


Importing Matplotlib – Simple line plots – Simple scatter plots – visualizing errors – density and
contour plots – Histograms – legends – colors – subplots – text and annotation – customization –
three dimensional plotting - Geographic Data with Basemap - Visualization with Seaborn.

TOTAL : 45 PERIODS
UNIT I CONTROLFLOW, FUNCTIONS, LISTS, TUPLES

Python interpreter – Data types – variables - expressions - Boolean values and operators -
Conditionals: conditional (if) - alternative (if-else) - chained conditional (if- elif-else);Iteration:
while - for - break - continue - pass; Fruitful functions: return values- parameters - local and global
scope - function composition - recursion; Strings - String Operations - Lists as arrays. Lists: list
operations - list slices - list methods - list loop - mutability - aliasing - cloning lists - list parameters;
Tuples: tuple assignment - tuple as return value

1. Outline the modes Python interpreter works. (2 MARKS) (NOV 2017)


2. What is list in python? Give an example. (2 MARKS) (NOV 2017)
3.Difference between compiler and interpreter. (2 MARKS) (NOV 2019)

INTRODUCTION TO PYTHON:

Python is a popular programming language. Python is a general -purpose


interpreted, interactive, object-oriented and high-levelprogramming language. Python
was developed by Guido Van Rossum at the National Research Institute for Mathematics
and Computer Sciences in late eighties and early nineties.

Uses:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

Python can do,

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Need for Python:

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python Syntax compared to other programming languages:

 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope
of loops, functions and classes. Other programming languages often use curly-
brackets for this purpose.

Python features:

 Easy-to-learn: Python has an extraordinarily simple syntax and hence it is easy-


to- learn for beginners.
 Easy-to-maintain: Python’s source code is easy-to-maintain.
 Extensive libraries: The python standard library is huge. A library is a collection of
precompiled routines that a program can use. Using python library various things
can be done like regular expressions, documentation, generation, unit testing,
email, cryptography, GUI, etc.
 Interactive mode: Python has shell prompt that provides interactive mode of
writing, testing and debugging python code.
 Extensible: Python is extensible (ie.) a critical piece of code can be in C or C++
andpython can use that piece of code in it.
 Portable: Python can run on a wide variety of platforms .Due to its open
sourcenature, python has been ported to (i.e. changed to make it work on) many
platforms.
 Scalable: Python provides a better structure and support for large programs. An
interpreter reads a high-level program and executes it. It process the program a
little at a time, alternately, reading lines and performing computations.

PYTHON INTERPRETER:

Python is processed at runtime by the interpreter. The python interpreter is a


program that reads and executes python code. Therefore, it is not necessary to compile
the program before executing it.

PYTHON IS INTERACTIVE:

Python has two basic modes: script and interactive.

 The normal mode is the mode where the scripted and finished .py files are run in
the Python interpreter.
 Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory. As new
lines are fed into the interpreter, the fed program is evaluated both in part and in
whole.
 Interactive mode is a good way to play around and try variations on syntax.
 On macOS or linux, open a terminal and simply type "python". On Windows, bring
up the command prompt and type "py", or start an interactive Python session by
selecting "Python (command line)", "IDLE", or similar program from the task bar
/ app menu. IDLE is a GUI which includes both an interactive mode and options to
edit and run files.

Python should print something like this:

$ python
Python 3.0b3 (r30b3:66303, Sep 8 2008, 14:01:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> is Python's way of telling you that you are in interactive mode. In interactive
mode what you type is immediately run. Try typing 1+1 in. Python will respond with 2.
Interactive mode allows you to test out and see what Python will do. If you ever feel the
need to play with new Python statements, go into interactive mode and try them out.

A sample interactive session:


>>> 5
5
>>> print(5*7)
35
>>> "hello" * 2
'hellohello'
>>> "hello". class
<type 'str'>

However, you need to be careful in the interactive environment to avoid confusion.

Python provides a prompt or interactive shell using which the users can interact with the
interpreter directly to write programs. The shell prompt (or command line) is one where
one types commands. The shell is the main way of accessing program and doing work on
the system.

Python is object oriented,

Python is an objected oriented programming language. Everything in python is an


object. Using python we can create classes and objects.

Classes: Class is like a blueprint that helps to create an object. In other words, a class
comprises variables, methods, functions. Or you can refer class which contains properties
and behavior. For example Consider a class “Ball” now the properties of Ball might be
color, diameter, price and the behavior of the ball might be rolling, bouncing.

Objects: Objects are an instance of a class. With the help of objects, we can access the
method and function of a class.
Python is beginner’s language,

Python is an easy-to-learn programming language and hence very useful for


beginner-level programmers.

COMPILER:

Compiler reads the program and translates it completely before the program
executes. The high-level program is called the source code and the translated programis
called the object code or executable code.

Difference between an Interpreter and a Compiler:

Interpreter Compiler

Translates program one statement at a time Scans the entire program and translates it as
a
Whole into machine code.
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time source code but the overall execution time is
is slower. Comparatively faster.

No intermediate object code is generated. Generates intermediate object code.

Continues translating the program until the It generates the error message only after
first error is met, in which case it stops. scanning the whole program. Hence
Hence debugging is easy. debugging is comparatively hard.

Programming language like python, Ruby Programming language like C,C++ use
uses interpreters. Compilers.
Python is considered an interpreted language because python programs are
executed byan interpreter. The command line is the most straight forward way to work
with python. Thereare different ways to access python’s command line depending on the
operating system installedon machine. In windows, python command line can be started
by clicking on its icon or menu item on start menu. In Linux, UNIX and Mac OS systems,
we have to run the terminal tool and enter pythoncommand to start.
There are 2 versions of Python, called Python 2 and Python 3. When python
starts, we seeoutput like this:

Python 3.4.0(default, Jun 21 2017,14:30:36)[GCC 4.8.2] on linux


Type “help”, ”copyright”, ”credits”, or “license” for more
information.
>>>

The first three lines contain information about the interpreter and the operating system
it’s running on. The versions number which is 3.4.0 in this eg begins with 3 which
indicates itis python it is python 3 version. The last line >>> is a prompt that indicates
that the interpreteris ready for us to enter code.

There are 2 ways to use the interpreter:


(i) Interactive mode
(ii) Script mode.

Interactive Mode:
In interactive mode, we type python programs and the interpreter displays the
result. The chevron, >>>, is the prompt that indicates the interpreter is ready to use.
>>> 2+2
4

Script Mode:
The code can be stored in a file and the interpreter is used to execute the
contents of the file which is called scripts. Python scripts have names that end with py.

Example program:

Python program to print “Hello , World !”


>>>print (‘Hello , world!’)

This is an e.g. of a print statement, that displays result on the screen. In this, the result
is the words.
Hello , World !

The quotation marks in the program mark the beginning and end of text to be displayed;
they don’t appear. The parenthesis indicates that print is a function. In python 2, the print
statement is slightly different; it is a function & hence doesn’t use parenthesis.

>>> print ‘Hello , World!’.


EXECUTION OF A PYTHON PROGRAM:

Python language is an interpreted programming or a script language, whereas


python isboth an interpreted and a compiled language. Python code is translated into an
intermediate code, which has to be executed by a virtual machine known as Python
Virtual Machine (PVM).Assume a python program first.py, where first is the name of
the program and .py is the extension.
The next step is to compile the program using python compiler. The complier
convertsthe python into byte code.
Byte Code – is the set of instructions that represents all operations which can run
on any OS. i.e., Byte instructions are platform independent. The size of each byte code
instruction is 1 byte. These byte code instructions are stored in first.pyc[Python Compiled
File]
The next step is to run the program. The byte code cannot be executed directly
because the computer can execute only binary (or) machine code which comprises 0’s
and1’s. PVM uses an interpreter which understands byte code and converts it into binary
code. PVM converts binary code into machine code understandable by the 0S. These
machine code instructions areexecuted by the processor.

DEBUGGING:

 The module pdb defines an interactive source code debugger for Python programs.
It supports setting (conditional) breakpoints and single stepping at the source line
level, inspection of stack frames, source code listing, and evaluation of arbitrary
Python code in the context of any stack frame.
 It also supports post-mortem debugging and can be called under program control.
 The debugger is extensible – it is actually defined as the class Pdb.
 This is currently undocumented but easily understood by reading the source.
 The extension interface uses the modules bdb and cmd.
 Programming is a complex process, and because it is done by human beings, it
often leads to errors. Programming errors are called bugs and the process of
tracking them down and correcting them is called debugging.

Three kinds of errors can occur in a program:

1. Syntax errors
2. Runtime errors
3. Semantic errors.
1) SYNTAX ERRORS:

Python can only execute a program if the program is syntactically correct;


otherwise, the process failsand returns an error message. Syntax refers to the structure
of a program and the rules about that structure. For example, in English, a sentence must
begin with a capital letter and end with a period. This sentence contains a syntax error. If
there is a single syntax error anywhere in your program, Pythonwill display an error
message and quit, and you will not be able to run your program.

Here are some ways to avoid the most common syntax errors:

 Make sure you are not using a Python keyword for a variable name.
 Check that you have a colon at the end of the header of every compound
statement, including for,while, if, and def statements.
 Make sure that any strings in the code have matching quotation marks.
 If you have multiline strings with triple quotes (single or double), make sure you
have terminated the string properly. An unterminated string may cause an invalid
token error at the end of your program, or it may treat the following part of the
program as a string until it comes to the next string.

In the second case, it might not produce an error message at all!

 An unclosed opening operator—(, {, or [—makes Python continue with the next


line as part of the current statement. Generally, an error occurs almost
immediately in the next line.
 Check for the classic = instead of == inside a conditional.
 Check the indentation to make sure it lines up the way it is supposed to. Python
can handle space and tabs, but if you mix them it can cause problems. The best way
to avoid this problem is to use a text editor that knows about Python and generates
consistent indentation.

2) RUNTIME ERRORS:

The second type of error is a runtime error, so called because the error does not
appear until you run the program. These errors are also called exceptions because they
usually indicate that something exceptional (and bad) has happened.

3) SEMANTICS ERRORS:

 The third type of error is the semantic error. If there is a semantic error in your
program, it will run successfully, in the sense that the computer will not generate
any error messages, but it will not do theright thing.
 It will do something else. Specifically, it will do what you told it to do. The problem
is thatthe program you wrote is not the program you wanted to write.
 The meaning of the program (its semantics) is wrong.
 Identifying semantic errors can be tricky because it requires you to work
backward by looking at the output of the program and trying to figure out what it
is doing.
1. Explain the various data types in Python. (8 MARKS) (NOV 2017)
2. What are keywords? Give examples. (2 MARKS) (JAN 2019)
3. Mention the list of keywords available in python. Compare it with variable name.
(8 MARKS) (APR2019)
4. What are statements? How they are constructed from variables and expressions in
python? (8 MARKS) (APR2019)
5. Outline the data types supported by python with an example.
(8 MARKS) (JAN 2022)
6. Are comments executable statements in a python program ? How comments are
included in python program? (2 MARKS) (JAN 2022)

DATA TYPES:

Type represents the kind of value and determines how the value can be used. All
data values in Python are represented as an object and every object has an identify, atype
and a value. Identifier is a name given to a function, class, variable.

It is the type of data, to access within the program. Data types are the
classification or categorization of data items. It represents the kind of value that tells what
operations can be performed on a particular data. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these
classes.

Python supports different data types, and each data type may have predefined
memoryrequirement and storage representation. The data stored in memory can be of
many types. Variables can store data of different types, and different types can do
different things.
For e.g., a person’s age is stored as a numeric value and his/her address is stored as
alphanumeric.

Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

INT:

Integer are whole numbers without decimal point. They can be positive or negative
as long as they don’t contain a decimal point. Integers have unlimited size in python.
Regular integers are normal integer numbers.
>>> a = 92
>>> b = -138

FLOAT:

They represent floating point numbers and it signify real numbers. Floats are
writtenwith a decimal point that segregates the integer from the fractional numbers.
>>>c = 14.95
They may also be written in scientific notation where e or e signifies 10th power

>>>3.3e3
>>>52.5e2
3300.0
5250.0

Conversion of Number types


Python converts one number type to another explicitly. To convert ‘x’ to a float.
>>> float(15)
>>>int(15.2)

15.0
15
BOOLEAN:

Boolean is a data type having 2 values true and false. The Boolean data type is the
resultof conditional statements which allow different actions and change control flow
depending on whether a programmer-specified Boolean contain evaluates to true or false.
>>>print(2==2)
>>>a=(2>3)
True
>>>print(2<3)
False

STRINGS:

Strings are identified as a contiguous set of characters represented in the quotation


marks [single +or double quotes]. Python does not support a character type. They are
treated as strings of length one.

Accessing values in Strings:

Subsets of strings can be taken using the slicing operator ([] and [:]) with index
startingat 0 in the beginning of the string. The plus (+) sign is the string concatenation
operator and the asterisk (*) is the repetition operator.
>>>str= ‘Python Programming’
>>>print(str)
Python Programming
>>>print(str[0:6])
Python
>>>print(str[7:])
Programming
>>>print(str*2)
Python Programming Python Programming
>>>print(str+ “ language”)
Python Programming language

Updating Strings:

An existing string can be updated by reassigning a variable to another string.


>>>str= ‘Python Programming’
print(‘Updated string:’,str[:7]+ ‘language’)
Updated string: Python language

String Formatting Operator:

>>>print(‘My name is %s from %s department’%(‘ADLIE’, ‘IT’))


My name is ADLIE from IT department

LISTS:
 Lists represent Python’s compound data types. A list contains items
separated by commas and enclosed within square bracket [].
 Items in the list can be different data type.
 The values stored in the list can be accessed using the slice operator ([] & [:])
with index starting at 0.
 The plus (+) is the concatenation operator and the asterisk (*) is the
repetition operator.

>>>list1 = [‘IT’, 9293, 13.08, ‘RIT’, 15.5]


>>>list2 = [928, ‘DEPT’]
>>>print(list1)
[‘IT’, 9293, 13.08, ‘RIT’, 15.5]
>>>print(list1[0])IT
>>>print(list1[1:3])[9293, 13.08]
>>>print(list1[2:]) [13.08, ‘RIT’, 15.5]
>>>print(list2*2)
[928, ‘DEPT’, 928, ‘DEPT’]
>>>print(list1 + list2)
[‘IT’, 9293, 13.08, ‘RIT’, 15.5, 928, ‘DEPT’]

TYPES:

A value is one of the basic things of a program and it works with like a letter or
a number. Some values are 2, 42.0 and ‘Python’. These values belong to different data
types: 2 is an integer, 42.0 is a floating point number and ‘Python’ is a string. If we are not
sure about the type a value has, then the interpreter will tell us about the data type.
>>>type(2)
<class ‘int>
>>>type(42.0)
<class ‘float’>

>>>type(‘Python’)
<class ‘str’>

In the results, ‘class’ is used to represent category; a type is a category of values.


If numbers are given in quotation, then it will consider it as string.
>>>type(‘2’)
<class ‘str’>

When we use large integer, we use commas between groups of digits, as in 1,000,000.
This is not a legal integer in Python.
>>>1,000,000
(1, 0, 0)
Python interprets 1,000,000 as a comma-separated sequence of integers.

VARIABLES:

A variable is a name that represents or refers to a value. Variables are reserved


memory locations to store values. The data type of a variable is based on the interpreter
which allocates memory and decides what can be stored in the reserved memory.

Rules:

 Variable names can contain uppercase (A-Z) letters, lowercase (a-z) letters,
digits(0-9) and underscore (_). E.g.) lastname, firstname, address1
 Variable names are case sensitive. E.g.) Name, name, NAME are 3 different
variables
 Numbers should not be used at the beginning of variable name. Eg) name1 is
validbut 1name is not valid.
 Camel case notations can be used. Camel case is writing compound words
withmixed casing. E.g.) thisIsAvailableName
 No special symbols other than underscore (_) are allowed.
 There are some reserved keywords that cannot be used as variable names because
they already have predefined meanings in python eg) print, input, if, while etc.

Assigning values to a variable:

 Python variable do not need explicit declaration to reserve memory space. The
declaration happens automatically while assigning value to a variable.
 The equal (=) sign is used to assign value to a variable.
Syntax: variable_name = value
Example:
name = “RIT”
dept = “CSE”
print(name)
print(dept)
Output:
RIT
CSE

IDENTIFIER:

Identifier is a name used to identify a variable, function, class, module, etc.


The identifier is a combination of character digits and underscore. The identifier should
start with a character or Underscore then use a digit. The characters are A-Z or a-z, an
Underscore ( _ ) , and digit (0-9). we should not use special characters ( #, @, $, %, ! ) in
identifiers.

Examples of valid identifiers:


var1
_var1
_1_var
var_1

Examples of invalid identifiers:


!var1
1var
1_var
var#1

KEYWORDS:

Keywords are the reserved words in Python. They are used to define the syntax
and structure of the python language. In python, keywords are case sensitive. There are
33 keywords in python. Each keyword performs a specific task.

You can get a list of available keywords by using help():

>>> help("keywords")

Here is a list of the Python keywords. Enter any keyword to get more help.

False class from or


None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
To retrieve the keyword in python,the following code can be given in prompt.
>>>import keyword
>>>print(keyword.kwlist)
Output:
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’,
‘del’, ‘elif’,
‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’,
‘nonlocal’,
‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

EXPRESSIONS:

An expression is a combination of values, variables and operators. If an


expression is typed in the command line, the interpreter evaluates it and displays the
result. i.e.) the interpreter finds the value of the expression. A value by itself is considered
an expression andalso a variable is considered an expression.
>>42
42
>>n18
>>n+1230

STATEMENTS:

A statement is a unit of code that the python interpreter can execute i.e.) it
doeswhatever the statement says.

>>n=17
>>print(n)

The first line is an assignment statement that gives a value to n. The second line is a
print statement that displays the value of n.

TUPLE ASSIGNMENT:

By tuple assignment, it is possible to assign multiple variables in one


statement. Atuple is the list of expressions separated by a comma.
e.g.) x, y, z = 100, -45, 0
x, y, z is a one tuple and 100, -45, 0 is another tuple. The first variable in left side tuple is
assigned the first value from the side tuple. i.e.) x = 100 similarly y = -45 and z = 0

COMMENTS:

A comment is a text that the interpreter ignores but provides useful


documentation to programmers. A single line comment statement starts with a hash (#)
symbol. A multiline comment statement starts and ends with either tuple single (‘’’) or
triple double quotes (“””). The author of a program can include his / her name and brief
statement about the purpose of the program at the beginning of the program file. This
type of comment is called as a docstring.
Example 1:
#Author: XXX
#Program to explain single line comments in python
stud_name = “AAAA” #name of the student
stud_marks = 100 #mark obtained by the student
print(stud_name)
print(stud_marks)
Example 2:
#program to explain Multiline comments
“ “ “print(“XXX”)
print(“YYY”)” ” ”
print(“ZZZ”) #outside the comment line.ZZZ

QUOTATIONS:

The single (‘), double (“) and triple (‘‘‘ or “““) quotations are used in python
torepresent string literal. The same type of quotes must begin and end that string

Example:
>>>print(‘XXX’)XXX
>>>print(“YYY”)YYY
>>>print(“““ZZZ”””)ZZZ

1. Outline with an example the assignment operators supported in Python.


(8 MARKS) (NOV 2017)
2. State about logical operators available in python with an example.
(2 MARKS) (APR 2019)
3. Describe the concept of precedence and associativity of operators with example.
(8 MARKS) (APR2019)
4. Name the types of operators supported by python and Outline any two with an
example. (8 MARKS) (JAN 2022)
5. In python, how the values stored in list are accessed? Should the elements of a list
be of the same data type? (2 MARKS) (JAN 2022)

OPERATORS:

An operator is a symbol that represents an operation to be performed on one


or more operands. An operand is a data item or quantity on which an operation is
performed. The operators that require two operands are called as binary operators and
the operators that require one operand is called as unary operators. Python is strongly
typed programming language. The interpreter checks data types of all operands before
operators are applied to those operands. If the type of an operand is not appropriate, the
interpreter halts execution with an error message. Consider the expression A = B + C. Here
A, B and C are the operands. The sign + and = are operators. Python provides different
operators.
They are classified as follows,

 Arithmetic operators: +, -, *, /, %, **, //


 Relational or comparison operators: <, >, <=, >=, !=, <>, == 3. Assignment
operator: =, +=, -=, *=, /=, %=, //=, **=
 Bitwise operator: &, |, ^, ~, <<, >>
 Logical operator: or, and, not
 Membership operator: in, not in
 Identity operator: is, is not
 Unary operator: -

ARITHMETIC OPERATORS:

Arithmetic operators are used to perform basic arithmetic operations. An


arithmetic expression consists of operands and operators.

Example:
x, y, z=40, 5, 4
print(“Sum =”,(x+y))
sum = 45
print(“Difference = ”,(x-y))
Difference = 35
print(“Product = ”,(x*y))
Product = 200
#True division always return float value
print(“Division = ”,(x/y))
Division = 8.0
print(“Remainder = ”,(x%y))
Remainder = 0
print(“Exponent = ”,(y**2))
Exponent = 25
#Truncating division returns rounded value
print(“Floor Division”,(y//z))
Floor Division = 1

The lists of arithmetic operators in python are,

S.NO OPERATOR OPERATION DESCRIPTION


It adds two operands.E.g.) x+y
1. + Addition

It subtracts right hand operand from the leftE.g.)


2. - Subtraction x-y
It multiplies two operandsE.g.) x*y
3. * Multiplication

It divides left hand operand by right and returns


5. % Modulo division the remainder
E.g.) x%y

In the quotient of the division operator, the digits


after decimal point are removed. But if one of the
6. // Floor division operands is negative, the result is floored i.e.)
rounded away from zero E.g.) x//y
The exponentiation operator (**) returns the result
7. ** Exponent of raising the first operand to the power of the
second operand. It is equivalent to Math.pow(),
except it also accepts BigInts as operands.

RELATIONAL (OR) COMPARISON OPERATORS:

Comparison operators evaluate or compare the values on either side of the


expression and it returns either True or False. It describes the relation between the left
and right operands.It is also called as Relational operators.

Example:
x, y = 40, 5
print(“Greater than = ”,(x>y))
Greater than = True
print(“Less than = ”,(x<y))
Less than = False
print(“Equals to = ”,(x==y))
Equals to = False
print(“Not Equals to = ”,(x!=y))
Not Equals to = True
print(“Greater than or equal to = ”,(x>=y))
Greater than or equal to = True
print(“Less than or equal to = ”,(x<=y))
Less than or equal to = False

The lists of relational operators in python are,

S.NO OPERATOR OPERATION DESCRIPTION


Checks if the value of left operand is less than the
1. < Less than value of the right operand, if yes then
thecondition becomes true. E.g.) x<y
Checks if the value of left operand is greaterthan
2. > Greater than the value of the right operand, if yes thenthe
condition becomes true. E.g.) x>y

3. Checks if the values of two operands are


== Equals equal,
if yes then the condition becomes true. E.g.)
x==y
4. Checks if the values of two operands not are
!= Not equals equal, if yes then the condition becomes true.
E.g.) x!=y

Checks if the value of left operand is less than or


5. <= Less than equal to equal to the value of the right operand, if yesthen
the condition becomes true. E.g.) x<=y
Checks if the value of left operand is greaterthan
6. >= Greater than equal to or equal to the value of the right operand,if yes
then the condition becomes true. E.g.) x>=y

ASSIGNMENT OPERATORS:

Assignment operators are used to assign a value or an expression or


value of avariable to another variable.

Syntax: variable = expression (or) value


e.g.) x = y, x = 10, x = a + b

Example:
x = 10, y = 5
x+=y
print(“Add = ”,x)
Add = 15
x-=y
print(“Subtract = ”,x)
Subtract = 10
x*=y
print(“Multiply = ”,x)
Multiply = 50
x/=y
print(“Division = ”,x)
Division = 10.0
x=2
x%=y
print(“Modulus = ”,x)
Modulus = 2
x**=y
print(“Exponent = ”,x)
Exponent = 32
x//=y
print(“Floor Division = ”,x)
Floor Division = 6

The lists of assignment operators in python are,

S.NO OPERATOR OPERATION DESCRIPTION


1. It assigns the values from right hand
‘=’ Assign operator toleft hand operator. E.g.) x = y

It adds right operand to left operand and


2. ‘+=’ Add and Assign assignthe result to left operand e.g.) x+=y i.e.)
x=x+y
It subtracts right operand from left operand
3. ‘-=’ Subtract and Assign and
assign the result to left operand e.g.) x-=y
i.e.)x=x-y
It Multiply two operands and assign the
4. ‘*=’ Multiply and Assign result toleft operand e.g.) x*=y i.e.) x=x*y

5. It divides right operand to left operand


‘/=’ Divide and Assign and
assign the quotient to left operand e.g.) x/=y
i.e.)x=x/y
6. It performs modulo and assign the
‘%=’ Modulo and Assign remainder toleft operand e.g.) x%=y i.e.)
x=x%y
It performs exponential calculation and
7. ‘**=’ Exponent and Assign assignthe result to left operand e.g.) x**=y
i.e.)
x=x**y
Floor Division and It performs floor division and assign the
8. ‘//=’ Assign result toleft operand e.g.) x//=y i.e.) x=x//y

BITWISE OPERANDS:

Bitwise operators are operations that directly manipulate bits. In system, numbers
are represented with bits, a series of zeros and ones. It performs bit by bit operations and
returns binary coded output.
(i) Bitwise AND (&)
Bitwise AND compares each bits of first operand with the corresponding
bits of second operand. If both bits have an equal value, then it returns the
same value as output. If one of the operand differs, it returns zero (0).
Operand 1 Operand 2 Bitwise AND
0 0 0
0 1 0
1 0 0
1 1 1
(ii) Bitwise OR (|)
Bitwise OR compares each bits of first operand with the corresponding
bits of second operand. If both bits have an equal value, then it returns the
same value as output. If one of the operand differs, it returns one (1).
Operand 1 Operand 2 Bitwise OR
0 0 0
0 1 1
1 0 1
1 1 1
(iii) Bitwise XOR (^)
Bitwise XOR compares each bits of first operand with the corresponding
bits of second operand. If both bits have an equal value, then it returns the
zero as output. If one of the operand differs, it returns one (1).
Operand 1 Operand 2 Bitwise XOR
0 0 0
0 1 1
1 0 1
1 1 0
(iv) Bitwise Complement (~)
Bitwise complement is used to invert the bits of an integer. It replaces all
1’s with 0’s and vice-versa.

Operand Bitwise Complement (~)


0 1
1 0
Example:
x = 60 00111100
~x 1 1 0 0 0 0 1 1
(v) Left shift operator (<<)
It is a binary operator that shifts given number of bits towards left
hand side(operand <<n). Here, n is the number of bits to be shifted.
Example:
a = 60 << 2 0 0 1 1 1 1 0 0
Shift 2 bits towards left hand side. 0 0 on the left hand side gets removed.
0 0 1 1 1 1 0 0 << 2 1 1 1 1 0 0 0 0
(vi) Right shift operator (>>)
It is a binary operator that shifts given number of bits towards right
hand side(operand >>n). Here, n is the number of bits to be shifted.
Example:
a = 60 >> 2 0 0 1 1 1 1 0 0
Shift 2 bits towards right hand side. 0 0 on the left hand side gets
removed.
0 0 1 1 1 1 0 0 >> 2 0 0 0 0 1 1 1 1

Program:
x, y, z = 60, 13, 0
z=x&y
print(‘Bitwise AND = ’, z)
Bitwise AND = 12
z=x|y
print(‘Bitwise OR = ’, z)
Bitwise OR = 61
z=x^y
print(‘Bitwise XOR = ’, z)
Bitwise XOR = 49
z = ~x
print(‘Bitwise One’s complement = ’, z)
Bitwise One’s complement = -61
z = x << 2
print(‘Bitwise left shift operator = ’, z)
Bitwise left shift operator = 240
z = x >> 2
print(‘Bitwise right shift operator = ’, z)
Bitwise right shift operator = 15

LOGICAL OPERATORS:

Logical operators are used to compare and evaluate logical operations. Python
supports 3 logical operations.
 and (Logical AND) – if both the operands are true then condition evaluates to
true. Ifanyone of the operand is false, then the condition evaluates to false.
E.g.) x and y
 or (Logical OR) – if anyone the operand is true then condition evaluates to
true. Ifboth the operands are false, then the condition evaluates to false.
E.g.) x or y
 not (Logical NOT) – It returns false when the condition is true and vice versa.
E.g.)not(x)
Example:
x, y = 10, 10
print((x>=y) and (x==y)
True
x, y = 10, 5
print((x>y) and (y>x)
False
print((x>y) or (y>x)
True
print(not(x>y)
False

MEMBERSHIP OPERATORS:

Membership operators are used to test whether a value or variable is found in


sequence like string, list, tuple, set and dictionary. Python supports two membership
operators.

 in – Evaluates to true, if it finds a variable in specified sequence and false


otherwise.
E.g.) x in y
 not in – Evaluates to true, if it finds a variable not in specified sequence and false
otherwise.
E.g.) x not in y

Example:
x = “Python Programming”
y = {1, ‘a’, 2, ‘b’}
print(‘t’ in x)
True
print(‘Program’ in x)
True
print(‘in’ not in x)
False
Print(1 in y)
True
print(‘c’ not in y)
True

IDENTITY OPERATORS:

Identity operators are used to compare the memory location of two objects. It is
used to check whether 2 values (variables) are located on same part of the memory.
Python supports 2identity operators.
 is operator – Evaluates to true, if variables on either side of the operator point to
the same object & false otherwise.
E.g.) x is y
 is not operator – Evaluates to false, if variables on either side of the operator point
to the same object & true otherwise. E.g.) x is not y
Example:
x, y, z = 15, 15, 10
print(x is y)
True
print(x is z)
false
print(y is z)
false
print(x is not y)
false
print(x is not z)
true
print(y is not z)
true

UNARY ARITHMETIC OPERATOR:

Python supports one unary arithmetic operators. Unary (-) minus – operator yields
the negation of its numeric argument
Example:
a = 10
print(-a)
-10

PRECEDENCE OF OPERATORS AND ASSOCIATIVITY OF OPERATORS:

Operator precedence:

 The operator precedence determines which operator needs to be evaluated


first in anexpression.
 Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated.
 Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operatorswill
be evaluated first.

The following table summarizes the operator precedence in Python, from highest
precedence to lowest precedence. When 2 operators have same precedence, Associativity
helps to determine the order of operations. All operators have left to right Associativity
except exponentiation which has right to left Associativity.
S.No Operator Operation
1. ** Exponentiation
2. ~, +, - Complement, unary plus and minus
3. *, /, %, // Multiply, divide, modulo, floor division
4. +, - Addition, Subtraction
5. >>, << Right and left bitwise shift
6. & Bitwise AND
7. ^, | Bitwise XOR and regular OR
8. <, <=, >, >= Comparison operators
9. ==, != Equality operators
10. =, %=, /=, //=, -=, +=, *=, Assignment operator
**=
11. is, is not Identity operators
12. in, not in Membership operators
13. not, or, and Logical operators

Associativity:

The associativity of operators determines the direction in which an expression is


evaluated. For example,
b = a;

Here, the value of a is assigned to b, and not the other way around. It's because the
associativity of the = operator is from right to left.

Associativity is the order in which an expression is evaluated, that has multiple


operator of same precedence. Every operator in Python has a precedence associated with
it. The operators of higher level precedence are evaluated first. The operators of same
precedence areevaluated either from left to right or from right to left depending onthe
Associativity level. For mathematical operators, Python uses mathematical convention.

The acronym PEDMAS is a way to remember rules.


 P – Parenthesis first
 E – Exponents (i.e. Powers, square roots, etc.)
 DM –Division Multiplication & (left-to-right)
 AS – Addition & Subtraction (left-to-right)
Rules for evaluation of expression:

 Evaluate the sub expressions from left to right if parenthesized.


 Evaluate the arithmetic expression from left to right using the rules of
precedence.
 The highest precedence is given to expression in parenthesis.
 Apply associative rule, if more operators of same precedence occurs.
 Evaluate the inner most sub expression if the parenthesis are nested.

Example:
(3-9) / 3 + 77 * (3-1)
-6 / 3 + 77 * 2
-2 + 154
152

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= Right to left


|=

Comma , Left to right


Example 1:
p = 20
q = 10
r = 15
s=5
t=0
t = (p+q) * r / s
print(t)
90
t = ((p+q) * r) / s
print(t)
90
t = (p+q) * (r / s)
print(t)
90
t = p + (q*r) / s
print(t)
50
Example 2:
print(10 * 2 // 3) # 10 * 2 = 20 , 20 // 3 = 6
6
print(10 * (2 // 3)) # 2 // 3 = 0, 10 * 0 = 0
0
//Right to left Associativity of ** (exponent) operator
print(2 ** 4 ** 2) # 4 ** 2 = 16, 2 ** 16 = 65536
65536
print((2 ** 4) ** 2) # 2 ** 4 = 16, 16 ** 2 = 256
256

INPUT / OUTPUT OPERATIONS

Every computer program has to communicate with the environment or outside


world. Every programming language has special I/O functionalities i.e. input / output. The
program takes some input data, processes it and gives the output. Python provides built-
in functions for I/O available to user at Python prompt.

1. Input:
Input often comes from the keyboard. It means data is entered by end-user of the
program. When a program executes, these functions are called and the system will freeze,
waiting for theend user to enter data.
Python provides 2 key functions for end-user input.

They are raw_input() and input().

raw_input() – This function reads one line from standard input and returns it as a string.

Syntax: raw_input([prompt])
variable_name = raw_input(“<prompt input statement>”)

Example:
>>>book_name=raw_input(“Enter book name:”)
Enter book name: Python
>>>book_name
Python

input() – It is equivalent to raw_input, except that it assumes the input as a valid


Python expression

Syntax: input([prompt])
variable_name = input(“<prompt input statement>”)

Example1:
>>>name=input(“Enter the name:”)
Enter the name: AAA
>>>nameAAA
The value entered in the input prompt is considered as String.
Example2:
>>>n=input(“Enter a number:”)
Enter a number: 4
>>>n‘4’
To convert this to a number int() method is used
>>>int(n)
4
The other way to convert String to int is
>>>n=int(input(“Enter a number:”))
Enter a number: 4
>>>n4
2. Output:

The print() function is used for formatting the output data to the standard
output device(screen). Zero or more expressions or statements can be passed to print()
function separated bycommas. It converts the expressions passed into a string and then
displays the result to standardoutput. The print() function always ends its output with a
new line. i.e. After displaying the output, the cursor moves to the next line.

Syntax: print(“<expression>”)
print(“<expression>”,variable_name)
Example
>>>print(‘Hello’)Hello
>>>a = 20
print(‘The value of a is:’,a)
The value of a is: 20
>>>sum = a + 30
print(‘The value of sum is:’,sum)
The value of sum is: 50

Output Formatting:

The output can be formatted by adding separator and end symbols.

Example1:
>>>print(1, 2, 3, 4, 5)
12345
>>>print(1,2,3,4,5,sep= ‘*’)
1*2*3*4*5
>>>print(1,2,3,4,5,sep= ‘#’, end= ‘&’)
1#2#3#4#5&
str.format() method can be used to format the output.

Example2:
>>>x = 10
>>>y = 20
>>>print(‘I am studying {0} in {1}’.format(‘IT’,‘RIT’))
I amstudying IT in RIT
>>>print(‘Hello {a}, {b}’.format(b=‘good morning’, a=‘everybody’))
Hello everybody, good morning

The % operator is a format operator. A conversion character associated with % operator


tells the format operator what type of value is going to be inserted in that position. 5d
specifies an integer, %f specifies float, %s specifies string, %c specifies single character

Example:
>>>print(‘My mark in %s is %d’ %(Python, 80))
My mark in Python is 80
>>>subject = ‘python’
>>>mark = 80
>>>print(‘My mark in %s is %d’ %(subject, mark))
My mark in Python is 80
>>>x = 123.45678
print(‘x = %3.2f’ %x)
x = 123.46
print(‘x = %3.4f’ %x)
x = 123.4568
ILLUSTRATIVE PROGRAMS(FOR REFERENCE)

1. How to find Distance between two points. (2 MARKS) (NOV 2019)


2. Write a program to exchange the values of two variables in different ways.
(8 MARKS) (JAN 2022)

EXCHANGE THE VALUES OF VARIABLES:

Exchange values of 2 variables can be done in different ways.


 Using temporary variable
 Without using temporary variable.

Method 1: Using temporary variable

a= int (input(‘Enter first value :’))


b= int (input(‘Enter second value :’))
temp=a
a=b
b= temp
print (‘After Swapping’)
print (‘First value:’, a)
print (‘second value:’, b)

OUTPUT:
Enter first value : 10
Enter second value : 20
After Swapping
First value : 20
Second value : 10

Method 2: Without using temporary variable

 Using tuple assignment:


a= int (input (‘ Enter first value:’)) b= int (input (‘Enter second value:’))
a,b=b,a
print (‘After Swapping’) print (‘First value:’ ,a) print (‘Second value:’, b)
 Using arithmetic operator:
Addition & Subtraction Multiplier & Divisiona=a+b a=a*b
b=a-bb=a/b
a=a-b a=a/b
 Using bitwise operator:
If variables are integers , then swapping can be done with help of bitwise
XORoperator.
a=a^bb=a^ba=a^b
CIRCULATE THE VALUE OF N VARIABLES:

Circulating a python list by an arbitrary number of items to the right or left can
be performed by list slicing operator. Circulation of the list by n position can be achieved
by slicing the array into two and concatenating them. Slicing is done as nth element to end
element + beginning element to n-1th element.

Example:
1, 2, 3, 4, 5, 6, 7
If n=2, then the given list is rotated 2 positions towards left side.
3, 4, 5, 6, 7, 1, 2 Left circulated list
If n=-2 then the given list is rotated 2 position towards right side.
6, 7, 1, 2, 3, 4, 5 Right circulated list.

Function to perform this circulation:

Method 1:
def circulate ( list , n):
return list [n:] + list [:n]
>>> circulate ([1, 2, 3, 4, 5, 6, 7], 2)
[3, 4, 5, 6, 7, 1, 2]
>>>circulate ([1, 2, 3, 4, 5, 6, 7] , 2)
[ 6, 7, 1, 2, 3, 4, 5]

Method 2:
n= int(input("Enter number of values : "))
list1 = []
for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,n,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)

Output:
Enter number of values : 5
Enter integer : 1
Enter integer : 2
Enter integer : 3
Enter integer : 4
Enter integer : 5
Circulating the elements of list [1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
TEST FOR LEAP YEAR:

Method1:

A leap year is exactly divisible by 4 except for century years (years ending with
00). The century year is a leap year only if it is perfectly divisible by 400.

For example,
2017 is not a leap year
1900 is a not leap year
2012 is a leap year
2000 is a leap year
Source Code
# Python program to check if year is a leap year or not

year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Output

2000 is leap year

Method 2:

Python provides isleap() function in calendar module to check whether a year is


leapyear or not .
>>> import calendar
>>> calendar ................ // provides info path
>>> calendar . isleap (2000)
True
>>> calendar . isleap (2003)
False
DISTANCE BETWEEN POINTS :

To find the distance between 2 points, given by the coordinates (X1,Y1) and
(X2,Y2), the Pythagorean theorem is used.

By the Pythagorean theorem, the distance is :


distance = ((x2-x1)2 + (y2-y1)2)
Example:

x1,y1,x2,y2=1,2,3,5
dx = x2 – x1 dy = y2 – y1

1. Write a Python program to accept two numbers, multiply them and print the result.
(2 MARKS) (JAN 2018)
2. Explain while loop with example.(or)Explain flow of execution of while loop with
Example. (2 MARKS) (JAN 2019)
3. Discuss conditional alternative and chained conditional in detail.(16MARKS) (NOV 2019)
4.
5. Outline the conditional breaking statements in python with an example.
(16 MARKS) (JAN 2022)
6. Outline the while loop, break statement and continue statement in python with example.
(12 MARKS) (JAN 2022)
7. Name the two types of iterative function supported by python. (12 MARKS) (JAN 2022)

CONTROL FLOW:

Control flow is the order in which individual statements, instructions of a program are
executed. In the program, all the instructions are executed sequentially by default. In some case, the
executions order of statements may change based on some condition or to repeat set of statements
until certain conditions are met.
Decision Making – if, if-else, elif, nested if... elif...else, inline if
Looping – for, while
Control structures – break, continue, pass

DECISION MAKING

Decision making constructs begins with Boolean expressions, an expression thatreturns


either True or False. It is necessary to perform an action or a calculation only when certain are met.

Python supports the following decision making statements:


 if statements
 If…else statements
 elif statements
 nested if….elif….else statements,Inline if

Conditional If Statements:

It is used to control the flow of execution of the statements and to logically test whether
the condition (Boolean expressions) is true or false. If the condition is true, then the true statements
are executed. The ‘true statements’ may be a single statements or group of statements. If the
condition is false, then the truestatements are not executed. In python, the true statements are
indicated by indentation.
Syntax:
if(condition):
True statements

Program 1:
a=200b=100
if a>b:
print( “a is greater than b”)

Output:
a is greater than b

Program 2: Interchange Values between 2 Variables


a=0
m= int (input (‘Enter the value for m:’ ))n= int (input (‘Enter the values for n:’)) if(m>n):
a=mb=n n=a
print(‘ The interchanged values are : ‘ , m, n)

Output:
Enter the value for m: 100Enter the value for n: 50
The interchanged value are: 50 , 100

Alternative if…else statement:

It is a 2 way decision making statement. It selects one of the two possible actions depending
on the condition test. If the conditionis true, then the True statements use executed. Ifthe condition
is false, then the False statements in else part is executed.

Syntax:
if (condition):
True statements
else:
False statements
Program 1:
a, b = 100, 200
if (a>b):
print (‘a is greater than b’)
else:
print (‘a is less than b’)

Output:
a is less than b

Program 2: To Find Whether Given Number Is Odd Or Even


n= int (input (‘Enter the number :’)rem = n%2
if (rem==0):
print (‘Even number’)
else:
print(‘odd number’)

Output:
Enter the number: 5Odd number
Enter the number: 26Even number

Chained Conditional If….Elif….Else Statements

An elif (else if) statement can be used to check or evaluate multiple expressions or
conditions. It first checks whether if condition is true. If it is true, then python executes if block
statements. If it is false, it checks the condition in elif block. If it is true, python executes elif block
statements.Otherwise, control goes to else block
Syntax:
if (condition 1):
if block statementselif (condition 2):
elif block statements
else:
statements

Program:
number = int (input(‘Enter a number :’))if(number>50):
print( ‘passed’)elif(number==50):
print(‘passed’)
else:
print(‘failed’)

Output:
Enter a number: 50Passed

Nested if else statements:


When a series of if..elsestatement occur, an entire if..else
statement can be written in another if..else statement. This is called nesting. Syntax:
if(condition1):
if(condition2):
True statement 2
else:
False statement 2
else:
False statement1
Program: To Check Whether Number Is Positive, Negative Or Zero

Num =int (input (‘Enter a number’))if (num>=0):


if (num==0):
print(‘zero’)
else:
print(‘Positive’)
else:
print(‘Negative’)

Output:

Enter a number:5
Positive
Enter a number: -4
Negative

nested if…elif…else statement:

Syntax:
if(condition1):
if(condition1a):
statement 1a
elif (condition1b):
statement 1b
else:
statement 1c
elif (condition2):
statement 2
else:
statement3
Program:

var=100
if var <200:
print (‘value less than 200’)if var==150:
print (‘value is 150’)else var==100:
print (‘value is 100’)
elif var==50:
print (‘value is 50’)elif var<50:
print (‘value is less than 50’)
else:
print (‘no value’)

Output:

Value less than 200


Value is 100

ITERATION – LOOPING

A loop is a programming control structure that facilitates the repetitive execution


of a statement or group of statements. The loop consists of 2 parts, one is the body of the loop
andother is control statement. The control statement is used to test the condition and then
directs the repeated execution of the statements in the body of the loop.

Looping statements include the following steps:


 Initialization of a condition variable
 Test the control statement
 Executing body of the loop depending on the condition
 Updating the condition variable

Python provides 2 looping constructs


 for loop
 while loop

FOR LOOP:

for loop executes a sequence of statementsfor a certain number of times using the
rangefunctions. The assignment, incrementation / decrementation and condition checking is
done infor statement.

Syntax:
for <variable> in <sequence>:statements
1) Looping through an iterable
In python, an iterable refers to anything that can be looped over such as a String, list,
and tuple.
Program 1:

message = ‘python’for i in message:


print(‘char is:’,i)

Output:

char is: pchar is: ychar is: t char is: hchar is: ochar is: n

Program 2:

language = [‘C’, ‘C++’, ‘java’, ‘python’]for x in language:


print(x)

Output:

C C++
java python

Program 3:

numbers = [10, 99, 3, 28, 41]


for i in numbers:
if(i % 2 == 0)
print(i, ‘is an even number’)
else
print(i,’is an odd number’)

Output:

10 is an even number
99 is an odd number 3
is an odd number 28 is
an even number41 is
an odd number

2) Looping through a sequence of numbers

To loops through a sequence of numbers, the built-in function range() is used toiterate
over for loops
Syntax:
range(start, end, step)
range() function produces the list iterates of numbers starting with start and generates
numbers with one less than the number end. Step is the difference between each number in
the sequence. It can be +ve or –ve but not zero. If start is not given, the numbers will start from
zero. If step is not specified, a list of consecutive numbers will be generated.

Example:
range(5) # Start and step not specified
o/p: [0 1 2 3 4]
range(3, 10)
list(range(3, 10))
o/p: [3 4 5 6 7 8 9]
range(4,10,2)
list(range(4, 10, 2))
o/p: [4 6 8]

Program 1:

for num in range(6):


print(num)

Output:
0
1
2
3
4
5

Program 2: To print weekdays using for loop with index

days = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’,‘Sunday’]


for index in range(len(days)): print(‘Week day:’, days[index])

Output:

Week day: Monday Week day: Tuesday Week day: Wednesday Week day: Thursday Weekday:
Friday Week day: Saturday Week day: Sunday

3) For loop with else


Python supports an else statement associated with a loop statement. If else is used within
for loop, it gets executed when the loop has finished iterating the list. A break statement
terminates for loop iteration.

Program: To find whether an item is present in the listlist


= [10, 12, 13, 34, 27]
num = int(input(‘Enter the no. to be searched:’))
for item in range(len(list1)):
if(list[item] == num):
print(‘Item found at:’,(item+1))
break
else:
print(‘item not found’)

Output: Enter the no. to be searched: 13


Item found at: 3

WHILE LOOP:

While loop is used when there is a need to repeatedly execute a statement or group
of statements. The while loop isan entry-controlled loop statement, which means the condition
is evaluated first and if it is true, then the body of the loop is executed. After executing the body
of the loop, the condition is once again evaluated and if it is true, the body is executed once
again. The process of repeated execution continues until the condition becomes false. When
condition becomes false, the program control passes to the line after the loop.

Syntax:

while(condition):
body of the loop

Program 1: To print sequence of numbers


counter = 0
while(counter < 4):
print(‘Count is:’, counter)counter = counter + 1print(‘Exit
of the loop’)

Output:
0
1
2
3
Exit of the loop

Program 2: Addition of 10 numbers


i=1
sum = 0
while(i <= 10):
sum = sum + ii = i + 1 print(‘Sum
of numbers =’,sum)
Output:
Sum of numbers = 55

Program 3: To print reverse of the given number


rev = 0
n=0
n = int(input(‘Enter the number:’))
while(n!=0):
r = int(n) % 10
rev = (rev * 10) + rn = int(n/10)
print(‘Reverse of given number:’,rev)

Output:
Enter the number: 9243 Reverse
of given number: 3429

while loop with else:


Python supports else statement associated with while loop. If the else statement
is used with a while loop, the else statement is executed when the condition becomes false.
Program:

i=0
while(i < 5):
print(i, ‘is less than 5’)i
=i+1
else
print(i, ‘is not less than 5’)

Output:

is less than 5 is
less than 5 is
less than 5 is
less than 5 is
less than 5
is not less than 5

Python Nested Loops:

While / for loop is also nested. The loop within the loop is called nested loop. In nested
while / for, two or more while / for statements are included in the body of the loop.The number
of iterations of this structure will be equal to the number of iterations in outer loop multiplied
by the number of iterations in the inner loop. On loop nesting, we can put anytype of loop inside
any other type of loop.
E.g.) a for loop can be inside a while loop or vice versa.
Syntax:
for <variable> in <sequqence>:
for <variable> in <sequqence>:Statements
Statements
while(condition):
while(condition):
statements
statements

Program 1: To find prime numbers from 1 through 10 [nested for loop]for


num in range(1, 10):
for i in range(2, num):
if(num % i == 0):
j = num / i;
print(‘%d equals %d * %d’%(num, i, j))
break
else:
print(num,’is a prime number’)

Output:
1 is a prime number 2
is a prime number 3 is
a prime number 4
equals 2*2
5 is a prime number 6
equals 2*3
7 is a prime number 8
equals 2*4
9 equals 3*3
10 equals 2*5

Program 2: nested while loop


i=2
while(i < 10):
j=2
while(j <= (i/j)):if
not(i % j): break
j = j + 1 if(j
> i/j):
print(i, ‘is prime’)i
=i+1
Output:
2 is prime
3 is prime
5 is prime
7 is prime

TYPES OF LOOPS:

The loop can be divided into 2 types based on the nature of loop control variable assigned
for testing to control the execution of the loop.
Counter controlled loops
The counter controlled loops are used in a situation when the programmer already
knows exactly how many times the loop will be executed. It is also called as definite repetition
loop. The control variable is declared, initialized, tested and updated regularly.
Program:
i=1
sum = 0
while(i <= 10):
sum = sum + i;
i = i + 1 print(‘Sum =’,sum)

Sentinel controlled loops

The sentinel controlled loops are used in a situation when the programmer does not
know exactly how many times the loop will be executed. It is also called as indefinite repetition
loop. The control variable is called as sentinel variable.

Program:
i=1
sum = 0
while(i != 999):
i = int(input(‘Enter number:’))
sum = sum + i;
print(‘Sum =’,sum)

CONTROL STATEMENTS:

Control statements change the execution of program from normal sequence. i.e.) it
controls the flow of program execution o get desire behavior or result.

Python supports 3 control statements


1. break
2. continue
3. Pass
Break:
A break statement is used to end the execution of the current loop and control moves
to execute the statement after the loop. If break is inside a nested loop, it will terminate the
after the loop. If break is inside a nested loop, it will terminate the innermost loop. It can be
used with for / while loops.

Program 1:

num = 0
while(num < 10):
if(num == 5):
break print(num) num = num + 1
print(‘End of program’)
Output:
0
1
2
3
4
End of program

Continue:
The continue statement skips remaining statements in the present iteration and
redirects theprogram to next iteration. Continue returns the control to the beginning of the
loop. It rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop

Program 1: continue in for loop


for i in ‘Python’:
if i == ‘h’:
continue print(‘Current letter:’,i)

Output:
Current letter: PCurrent letter: yCurrent letter: t Current letter: oCurrent letter: n

Program 2: continue in while loop


n = 10;
while(n>0):
n = n -1 if n == 5:
continue
print(‘Current value: ’,n)
Output:
Current value: 9
Current value: 8
Current value: 7
Current value: 6
Current value: 4
Current value: 3
Current value: 2
Current value: 1
Current value: 0
Program 3: To find sum of given positive numbersn
= int(input(‘Enter upper limit’))
sum = 0
for x in range(1, n):
x = int(input(‘Enter no. to add: ’))
if(x < 0):
continue
else:
sum = sum + x
print(‘Sum is: ’,sum)
Output:
Enter upper limit: 5
Enter no. to add: 10
Enter no. to add: -10
Enter no. to add: 20
Enter no. to add: -5
Sum is: 30

Pass:
pass statement is a null operation i.e. nothing happens when it executes. It is used when
a statement is required syntactically but no need of command or code to execute. It is used as a
placeholder. A loop cannot have an empty body. So pass statement is used to construct a body
of loop that does nothing.
Program:
for i in ‘Python’:
if i == ‘h’:
pass
print(‘Pass block’)
print(‘Current letter: ’,i)
Output:
Current letter: P Current letter: y Current letter: t Current letter: h Current letter: o
Current letter: n
FUNCTIONS

1. What is recursion? (or) Define Recursion with an example.(2 MARKS) (JAN2019)


2. Explain global and local scope. (or) Comment with an example on the use of local
and global variable with the same identifier name. (2 MARKS) (MAY 2019)
3. Define recursive function. (2 MARKS) (JAN 2022)
4. Write a python program using function to find the sum of first n odd numbers and
print result. (4 MARKS) (JAN 2022)

Function:

A function is a set of instructions that are used to perform specified task which is
repeatedly used. Functions provide better modularity and a high degree of code reusing.
By using functions complex tasks can be sub-divided into manageable tasks. Functions are
known under various names in programming language example as routines, subroutines,
procedures, methods, subprograms. Python offers many built-in functions like print(), input()
and it also supports to generate our own functions called as user-defined functions.

Need-user-defined functions:

While writing a complex program, it leads to no. of problems, such as the program
becomes too large and complex and the task of debugging, testing and maintenance becomes
difficult. If a program is divided into parts, then each part may be independently coded and
later combined into single program. When some part of code is repeated in the program, then
they can be designed as a function, and canbe called and used as and when required. It saves
both time and memory.

Advantages:

 The length of the source program can be reduced by dividing it into smaller
functions.
 It is easy to locate and debug an error.
 User defined functions can be used in many other source programs whenever
necessary.
 It avoids coding of repeated instructions.
 It enables programmer to build customized library of repeatedly used routines.
 Its facilities top-down programming approach.

Function elements:

 Function Definition- The function definition contains the code that determines the
function behaviour.
 Function Invocation(call)
 Function Definition:
Component of function definition:

 Function block starts with the keyword def followed by the function name and pair
of parentheses ().
 Function name is used to distinctively identify it.
 The values are passed to the function with the help of parameters (or) arguments.
The parameters (or) arguments must be placed inside the parenthesis.
 A colon (:) symbol is used to indicate end of function header.
 The first statement of a function is an optional statement which is doc string.
 The function body consists of one or more valid python statements. All statements
should have similar indentation level
 The last statement return [expression] exits a function, optionally passing back on
expression to the caller. A return statement with no arguments is same as return None
By default, parameters have a positional behavior and we have to provide them in the
same order that they were defined.

Syntax

def funtionname(parameters):“functiondocstring”
Function body return [expression];
Function Invocation [function call]:

Once the structure of the function is defined, the function can be executed by calling it
from other function or program or even from python prompt.

Program 1:
def count_to_5():
for i in range(1,6):
print(i)
print (‘Function call to print numbers:’)
count_to_5()
print (‘Function call to print numbers again:’)
count_to_5()

Output:
Function call to print numbers: 12
3
4
5
Function call to print numbers again: 12
3
4
5
Program 2:

def cube(x):
y=x*x*x
print(y)
cube(3)

Output:

27

Program 3:

def odd_even(number):
if(number%2==0):
print (‘The number’,number,’is even’)
else:
print(‘The number’,number,’is odd’)
result = int(input(‘Enter a number:’))
odd_even(result)

Output:

Enter a number: 85
The number 85 is odd
Function argument:

In python, user-defined functions can take different types of arguments. The


arguments types and their meanings however are predefined and can’t be changed. But a
developer can follow these predefined rules to make their own custom functions.

Required Arguments:

Required arguments are the arguments passed to a function in correct positioned


order (i.e.) thenumber of arguments in function call should match exactly with the function
definition.

Example:

def printing(str):

‘“The prints string passed to the function”’print(str)


printing()

To call the function printings(), on arguments is compulsory, otherwise it gives syntax


error.
TypeError: printing() missing | required positional argument: ‘str’

Keyword arguments:

When the function is called with some values, these values get assigned to the
arguments according to their position. But python allows functions to be called using keyword
arguments. By keyword arguments, the caller identifies the arguments by the parameter name.
When the function is called in this method, the order(ie) the position of the arguments can be
changed.

Example:

def printinfo(name,phno):
print(“Name:”,name)
print(“phone no:”, phno)
#A function with 2 keyword arguments
printinfo (name=’xxx’, phno = 123456789)#A fn.call with out of order arguments
printinfo(phno= 123456789, name=’xxx’) #A fn.call with 2 positional arguments
printinfo(‘xxx’. 123456789) #A fn.call with | positional arguments & keyword argument
printinfo(‘xxx’,phno=123456789)

It is possible to mix positional arguments & keyword arguments. But keywordarguments


have tofollow positional arguments.
Placing a positional argument after keyword argument will result in error.
printinfo(name=’xxx’,123456789)

SyntaxError: positional argument follows keyword argument

Default Arguments:

Function parameters can be default values in python. A default value can be given to the
parameter by means of the assignment operator. Several no. of parameter in a function can
have a default value. But once the function has a default parameter, all the arguments to its
right must also have default value

Example:
def printfinfo (name,phno=’123456789’):
print(‘name=’,name)
print(phoneno=’,phone)
printinfo(name=’xxx’)
printinfo(name=’xxx’,phno=’567891234’)
In this function, the parameter name does not have a default value and is required during a call.
The parameter phno has a default value of ‘12456789’. So, it is optional during a call. If a value
is provided, it will overwrite the default value.
def printinfo(name=’AAA’,phno)

Syntax Error: non-default argument follows default argument.

Variable-length arguments:

In some cases, the programmers may not be familiar with the no.of arguments that
will be passed to a function. Python provides function calls with subjective number of
parameters. In the function definition, asterisk(*) before the arguments name is used to
indicate variable-length arguments.

Example:
def greeting (*person-name):
for name in person-name:
print(“Hai”,name)
greeting(“XXX”, “YYY”, “ZZZ”)
Output:

Hai XXXHai YYYHai ZZZ

Function parameters:

A function can take parameters, which are specified within pair of parentheses in
the function definition. The parameters are like variables except that the values of their
variables are defined in function call. The names given in the function definition are called
parameters whereas the values supplied in function call are called arguments.

Example:
def find_max (a,b):

if a>b:
print(a,’is max’ )
elif a==b:
print (a, ‘is equal to’,b)
else:
print(b,’is max’)
find_max(5,9)
x=46
y=76
find_max(x,y)

Function definition &

uses:Example:
def print_sample():
print(‘Hi’) print(‘Hello’)
def repeat_print():
print_sample()
print_sample()
repeat_print()

This program contains two function definitions: print_sample() and repeat_print().


Function definitionsgets executed like other statements, but creates function objects. The
statements inside the function do not run until the function is called. The function definition
has to run before the function gets called. Inthe above program, if the function call
repeat_print() appear before the definitions, then we get error message.

Flow of Execution:

Flow of execution specifies the order in which the statements run. Executionalways
begins at the first statement of program. Statements are run one at a time, in order from top
to bottom. Functiondefinition does not alter the flow of execution of the program, but the
statements inside the function don’t run until the function is called.
A function call is like a detour in the flow of exec instead of going to the next statements, the
flow jumps to the body of the function, runs the statements there, and then comes back to pick
up where it left it.

FRUITFUL FUNCTIONS-RETURN STATEMENT

The return statement in a function may or may not send back values to the
mainprogram (Calling Program). A function that returns back some useful values are called
as fruitful functions whereas functions that does not return anything are called as void
functions.
Program-Fruitful function:

def sum(a, b):


total = a + b
print(“Inside function: ”, total)
return total;
total = sum(100,200)
print(“Outside function:”,total)

Output:

Inside function: 300


Outside function: 300

SCOPE OF VARIABLES:

The scope of a variable determines the problem of the program where the user can
access it.
There are 2 basic scopes of variables in python:
Local and global scope.

Variables that are defined inside a function body have a local scope and those defined outside
have a global scope. The local variables can be accessed only inside the function in which they
are declared, whereas the global variables can be accessed throughout the program by all the
functions. When a variable is declared inside a function definition, they are not related in any
way to other variables with the same names used outside the function (i.e.) same variables
name can be used for local and global.

Program 1:

def fun (a):


a=12
print (a, id (a))
a=5
fun (a)
print (a, id (a))
Output:

12 1634817952
5 1634817940

In the function call fun(a), the object reference is passed . the object value is 5 & its name
is a. Inside the function fun () a=12 means a different object created in memory with value 12
and name a. This happens because integer objects are immutable.

Program 2:

def fun(list1):
list1.append (5)
print(list1, id (list1))
list1 = [1,2,3,4]
fun(list1) print(list1,
id(list1))

Output:

[1,2,3,4,5] 64667200
[1,2,3,4,5] 64667200

In the function call fun (list1) the object reference of list1 is passed. Inside the function,
a new element is appended to the list. Since lists are mutable, adding a new element to the same
object is possible, hence append () modifies the same object.
The Anonymous Function – Lambda

Lambda is the keyword used to create small functions. It lets to define one – line mini
functions on the fly. Python borrowed concept of lambda functions from lisp. Lambda functions
can have any number of arguments but only one expression. The expression is evaluated and
returned. It can be used wherever functions objects are required. An anonymous function
cannot be a direct call to print because lambda requires an expression. Lambda functions have
their own local namespace and cannot access variable other than those in their parameter list
and those in global namespace.

Syntax:

lambda [arg1[arg2,…argn]] : expression

Program 1
sum = lambda arg1,arg 2:arg1 + arg2
print(“total:”,sum (100,200))

Output:
Total: 300

Program 2
double = lambda n : n*2 print(“calling
lambda fn:”,double(10))

Output:
Calling lambda fn : 20

Program 3: lambda within lambda


add-two=lambda n : n+2
multiply-add-two=lambda n : add-two(n*2)
print (“lambda:”,add-two(3))
print(“lambda within lambda:”,multiply-add-two(3))

Output:
lambda: 5
lambda within lambda: 8

Use of lambda functions


 Lambda functions can be used when we require a nameless function for a short
periodof time.
 Lambda functions are used along with built-in functions like filter(), map(),etc.
Lambda function with filter():

The filter () function in python takes in a function and a list as arguments. The function
is called for all the items in the list and a new list is returned which contain items for which the
function evaluates to true.

The following example uses filter () fn to filter out only even numbers from a list.

Program
old-list=[21,25,24,27,30,28,32,33,34]
new-list=list(filter(lambda no : (no%2==0),old-list))
print (new-list)

Output:
[24,30,28,32,34]

Lambda function with map ():

The map () function in python takes in a function and a list. The function is calledwith
all the items in a list and a new list is returned which contains values provided by thefunctions
for each item. The following examples uses map () functions to double all the items in the list.

Program
old-list=[2,5,8,3,10,7]
new-list=[list(map(lambda no : no*2, old-list))
print (new-list)

Output:
[4,10,16,6,20,14]

FUNCTION COMPOSITION:

Function composition is a way of combining functions such that the result of each
function is passed as the argument of the next function. The composition of 2 functions f andg
can be denoted as f(g(x)), where x is the argument of g, the result of g is passed as argument of
f and the result of the composition is the result of f.

Syntax:
def compose(f, g):
return lambda *args : f(g(*args))
Program1:
def compose1(f , g):
return lambda x : f(g(x))
def double(x):
return x*2
def inc(x):
return x+1 inc_double=compose1 (double, inc)inc_double(10)

Output:
22
Program2:
def dec (x):
return x-1
inc_dec_double=compose1(compose1(dec, double),inc)
inc_dec_double(10)

RECURSION:

Recursion is a way of programming a problem, in which a function call itself one or more
times in its body. Recursion is the process of calling the same function itself again and again
until some condition is satisfied.

Syntax:
function1():
function1()

function1() is called itself continuously. So the above function is in recursive manner. If a


problem can be solved utilizing solutions to smaller versions of same problem, then we can use
a recursive algorithm to solve such problem.

Example: Factorial of given Number

n! = 1 * 2* 3. *n
i.e. n! = n * (n -1)!
This is a recursive statement of program, in which the desired action is expressed in termsof
preview results i.e. (n -1)!
Since 1! = 1, it provides the stopping condition also called as base conditionn! For any non-
negative integer is defined as

Program:
def factorial(n):
if n==1:
return 1
else
return n * factorial(n-1)
n = int(input(“Enter a number”)) print(“The
factorial of”, n, “is”, factorial(n))
STRING

1. Write a python code to search a string in the given list. (16 MARKS)(MAY 2018)
2. Write a python program to generate all permutations of a given string using built-in
function. (8 MARKS) (DEC 2019)
3. Write a program to display a set of strings using range( ) function.
(2 MARKS)(NOV 2019)
4. Discuss in detail about string slices and string immutability.
(16 MARKS)(JAN 2019)
5. Analyze String slicing. Illustrate how it is done in python with example.
(16 MARKS)(MAY 2019)

String:

A String is a sequence of characters delimited by single or double quotes.


Example:
>>> str= ‘Python’
>>>print(str)
Python
>>>letter=str[1] #This statement selects character from index 1 and creates new
String letter containing the character in index 1
>>>print(letter)y

The expression in brackets[] is called an index. Python always start counting fromzero
index. The len() function, returns the number of characters present in the string.
>>>str= ‘Python’
>>>size = len(str)
>>>print(size)6
>>>last = str[size]
Index error: string index out of range
>>>last = str[size-1]
>>>print(last)‘n’

Traversal:

String traversal start at the beginning, select each character in turn and continueuntilthe
end. The traversal can be done using for loop or while loop.

for loop:
str= ‘python’
for i in str:
print(i)

Output:
python
while loop:
str = ‘python ’i
=0
n =len(str)
while(i < n):
letter = str[i]
print(letter) i =
i+1

Output:
pyt hon

STRING SLICES:

A substring of a string is obtained by taking a slice. The slice operator [n:m] returns part
of the string from the nth character to (m-1)th character. If the first index before the colon is
missing i.e. [:m], the slice starts at the beginning of the string. If the second index after the colon
is missing i.e. [n:], the slice extends to the end of the string. If the second index value isbigger
than the length of the string, then the slice will take all the values up to the end.

Example:
>>>book = ‘Python programming’
>>>book[0:]
‘Python programming’
>>>book[7:] ‘programming’
>>>book[7:14]‘program’
>>>book[7:999]
‘programming’

IMMUTABILITY:

Strings are always immutable i.e. it does not allow to change an existing string. Hence,
it is not possible to use the slice[] operator on the left side of an assignment, with the
intention of changing a character in the string.

Example:
greet = ‘Hello’greet[0] = ‘M’
print(greet)
this produces the run time error. Type error: ‘str’ object does not support item assignment.
But it is possible to create a new string with the necessary changes in the original string.
greet = ‘Hello’
new_greet = ‘M’ + greet[1:]
print(new_greet)
Mello
STRING OPERATIONS:

Concatenation:
It is represented by the symbol ‘+’. It combines 2 strings into one string
Example:
str = ‘Python’ str1
= ‘Program
’print(str + str1)
PythonProgram

Repetition:
It is represented by the symbol ‘*’. It creates a new String by repeating the givenstring for
specified no. of times.

Example:
str = ‘Python’ print(str
* 3)
PythonPythonPython

Slicing:
It is represented by the symbol []. It prints the character at the given index.

Example:
str = ‘Python’
print(str [2])‘t’

Range Slicing:
It is represented by the symbol [:]. It prints the characters present in the given range.

Example:
str = ‘Python’
print(str[1:4])
yth

MEMBERSHIP OPERATORS:
in – returns True value if character is present in the given string
not in – returns True value if character is not present in the given string
Example1:
str = ‘Python’
print(‘t’ in str)
True Example2:
str = ‘Python’
print(‘t’ not in str)
False
STRING METHODS AND FUNCTIONS:

1) len()
It is used to determine the size of a string i.e. the number of characters in a string
Example:
str = ‘Python’
print(len(str))6

2) capitalize()
It will return a copy of the given string with the first character in upper case and the
remaining characters in lower case
Example:
str = ‘python programming’
print(str.capitalize()) Python
Programming

3) upper()
It will return a copy of the given string with all the characters in upper case

Example:
str = ‘python programming’
print(str.upper())
PYTHON PROGRAMMING

4) lower()
It will return a copy of the given string with all the characters in lower caseExample:
str = ‘python programming’
print(str.lower())
python programming

Boolean

Methods

1)isalnum()
It returns a Boolean value True if all the characters in the given string is alphanumericExample:
str = ‘python programming 1’
str1 = ‘python programming1’
print(str.isalnum())
False
print(str1.isalnum())
True

2) isalpha()
It returns a Boolean value True if all the characters in the given string isalphabets
Example:
str = ‘python programming’ str1
= ‘python programming1’
print(str.isalpha())
True
print(str1.isalpha())
False

3) isdigit()
It returns a Boolean value True if all the characters in the given string isnumeric
Example:
str = ‘python programming 1’
str1 = ‘12345’
print(str.isdigit())
False
print(str1.isdigit())
True

4) islower()
It returns a Boolean value True if all the characters in the given string is inlower case
Example:
str = ‘python programming’
print(str.islower())
True

5) isupper()
It returns a Boolean value True if all the characters in the given string are inupper case
Example:
str = ‘python programming’
print(str.isupper())
False
6) istitle()
It returns a Boolean value True if all the characters in the given string are intitle case
Example:
str = ‘Python Programming
’print(str.istitle())
True
7) isspace()
It returns True if given string contains only whitespaceExample:
str = ‘ ’ Print(str.isspace())
True
8) swapcase()
It returns a copy of the string in which all the case_based characters have their caseswapped
Example:
str = ‘Python Programming’
print(str.swapcase())
pYTHON pROGRAMMING

9) join()
It returns a string in which the string elements of sequence are joined by separator.Example:
sep = “_”
str = “python”
print(sep.join(str))
p_y_t_h_o_n
sep = “_”
str = “python”
print(sep.join(reversed(str)))
n_o_h_t_y_p
sep = “,”
str = “python”
print(sep.join(str))
p,y,t,h,o,n

10) split()
It splits a single multiword string into a list of individual words, removing all thewhite
space between them.
Example:
Book = “Problem Solving and Python Programming”
print(book.split())
[‘Problem’, ‘Solving’, ‘and’, ‘Python’, ‘Programming’]

11) replace()
It takes an original string and returns an updated string with some replacement.
Example:
print(book.replace(‘Programming’, ‘Language’))Problem
Solving and Python Language

12) count()
count(sub, [start, end])
It will return the total no. of occurrences of the given substring sub within the givenrange
of [start, end]. The start and end are optional arguments.
Example:
str = “String string String string String”
print(str.count(‘String’))
3
print(str.count(‘string’))2

13) index()
index(sub, [start, end])
It will return the lowest index of the given substring found in the slice s[start, end].The
start and end are optional arguments
Example:
str = “String string String”
print(str.index(‘String’)) 0
print(str.count(‘String’, 3))
14

14) endswith()
endswith(suffix, [start, end])
It will return a True value, if the string ends with the specified suffix, else returnFalse.
Example:
str = “String string String”
print(str.endswith(‘String’))
True
print(str.endswith(‘String’, 0, 13))
False

15) find()
find(sub, [start, end])
It will return the lowest index of the given substring in the string, if it is found inrange
[start, end]. Otherwise it will return -1
Example:
str = “String string String string”
print(str.find(‘String’))
7

FUNCTION PROTOTYPES:

The functions are classified depending on whether the arguments are presentor
notand whether a value is returned or not. These are also called function prototypes.

Function with no arguments and no return values


No data transfer between calling function and called function i.e. the called
programdoes not receive any data from the calling program and does not send back any value.

Program:
def add():
a = int(input(‘Enter value for a:’)) b
= int(input(‘Enter value for b:’))c=a
+b
print(‘Addition value: ’,c)
add() #function call
Output:
Enter value for a: 100 Enter
the value for b: 200
Addition value: 300

Function with arguments and no return values:


The called function receives some data from the calling function and does not sendbackany
value to calling function (one way communication).

Program:
def add(x, y):
z=x + y
print(‘Added value: ’,z)
a = int(input(‘Enter value for a:’)) b
= int(input(‘Enter value for b:’))
add(a, b)

Output:
Enter value for a: 100
Enter the value b: 200
Added value: 300

Function with no arguments and with return values:


The calling program does not pass any argument to the calling function. But the called
function return value back to the calling function (one way communication).

Program:
def mul(x, y):
a= int(input(‘Enter value for a:’)) b=
int(input(‘Enter value for b:’))
return(a*b)
prod = mul()
print(‘Multiplied value: ’, prod)

Output:
Enter value for a: 10
Enter the value b: 2
Multiplied value: 20

Function with arguments and with return values:


The called program receives some data from the calling function and returnsbackvalue
to the calling function(Two way communication)

Program:
def add(x, y)
z=x+y
return z
a = int(input(‘Enter value for a:’)) b
= int(input(‘Enter value for b:’))c =
add(a, b)
print(‘Added value: ’,c)

Output:
Enter value for a: 100
Enter the value b: 200
Added value: 300

CALL BY VALUE vs CALL BY REFERENCE

Call by value represents that the copy of the variable value are passed to the
function and any modification to that values will not reflect outside the function. Call by
reference represents passing the reference or memory address of the variable to the function.
The variable values are modified by the function through the memory address and hence the
modified values will reflect outside the function also. In python everything is considered as
an object. Numbers strings and other data type like lists, tuples and dictionaries objects. In
python, the values are passed to the functions by means of object reference. An object is a
memory block where some values can be stored.
Example:
a=10 an object with value 10 is created with name ‘a’.
To identify the location of an object in memory, python provides the function id(),thatgives
identity number of an object.
>>>a=10
>>>id(a) 1634817920

When we pass value to the function like numbers, strings lists or tuples, the reference of the
object are passed. Integer, Strings, floats, and tuples in python are immutable i.e. their data
cannot be modified and instead a new project will be created with the modified value lists and
dictionaries are mutable i.e. when their data is changed the same object gets modified and new
object is not created.

LISTS AS ARRAYS:

Programs in most cases uses list of variables. To store many variables, python can use a
data structure called Lists. List is called as arrays in most of the programming languages. A list
(array) is a set of objects. Individual objects can be accessed using ordered indexes
thatrepresent the position of each object within the list (array)

Example:

prime = [2,3,5,7,11,13]
The list prime has 6 elements
i.e. prime[0] = 2, prime[1] = 3 and so on.

The lists can also have negative index to start from the end of list i.e. prime[-1] = 13, prime[-2]
= 11 andso on. The length of the lists that is the number of elements in the lists can be obtained
using len().
len(prime) = 6

Creating and Reading lists:


Create an empty list. Then add items to the end of the list using append.

Example:
a = []
n = int(input(“Enter the no. of elements:”))
for i in range(n):
new_element = int(input(“Enter element:”))
a.append(new_element)
print(a)

Output:
Enter the no. of elements: 3
Enter element: 8
Enter element: 5
Enter element: 10
[8, 5, 10]

To print the elements in the list using loop:


a = [1,2,3,4,5]
for i in range(len(a)):
print(a[i])
a = [1,2,3,4,5]
for element in a:
print(element)
Output:
1
2
3
4
5

1
2
3
4
5
ILLUSTRATIVE PROGRAMS

1. Write a Python program to generate first ‘N’ Fibonacci series numbers. (Note: Fibonacci
numbers are 0,1,1,2,3,5,8… where each number is the sum of the preceding two)
(8 MARKS) (JAN 2018)
2.Write a Python program to perform binary search. (8 MARKS) (JAN 2019)

SQUARE ROOT OF A NUMBER: [NEWTON’S METHOD]

Program:
def newton(val, init):
def f(x):
return x**2-val
def derf(x):
return 2*x
for i in range(1, 25):
x3 =x4 =init = init – f(init) / derf(init)
print(init)
return init
val = int(input(‘Enter number’))
init= int(input(‘Enter base’))
newton(val, init)

GCD [GREATEST COMMON DIVISOR]EUCLIDEAN ALGORITHM:

Divide the greater by smaller and take the remainder. Divide the smaller by this
remainder. Repeat until the remainder is zero.

Example:
GCD(180, 30)
108 % 30 = 18
GCD(30, 18)
30 % 18 = 12
GCD(18, 12)
18 % 12 = 6
GCD(12, 6)
12 % 6 = 0
Hence GCD is 6

Program:

def gcd(a, b):


if(b == 0):
return a
else:
return gcd(b, a%b)
a = int(input(“Enter first no.”))
b = int(input(“Enter second no.”))
divisor = gcd(a, b)
print(‘GCD is: ’,divisor)

Output:

Enter first no: 108


Enter second number: 30
GCD is 6

EXPONENTIATION:

The simple way to find the exponentiation of a number xy in python is use of **


operator
>>>4 ** 3
64.0
Another way to find exponentiation is use of pow() function available in math module
>>>import math
>>>math.pow(4, 3)
64.0

User defined functions can also be written to find exponentiation

Program:
def power(base, exp):
if(exp == 1):
return baseif(exp != 1):
return (base*power(base, exp-1))
base = int(input(“Enter base: ”)) exp
= int(input(“Enter exp: ”))
print(‘Result is: ’,power(base, exp))

Output:
Enter base: 4
Enter exp: 3
Result is: 64.0

SUM OF ARRAY OF NUMBERS ITERATIVE SUMMATION PROGRAM:

The function uses an accumulator variable(sum) to compute a running total of all the
numbers in the list by starting with 0 and adding each number in the list.
Program:
def sum(numlist):
sum = 0
for i in numlist:
sum = sum + i
return sum
mylist = [1, 3, 4, 10, 5]
print(sum(mylist))

Recursive Summation Program:


The sum of numlist is the sum of the first element of the list numlist[0] and the sum of
rest of the numbers in the list.numlist[1:].
To state it in functional form
Sum(numlist) = first(numlist) + sum(rest(numlist))

Program:
def sum(numlist):
if len(numlis0 == 1:
return numlist[0]
else:
return numlist[0] + sum(numlist[1:])

mylist = [1, 3, 4 10, 5]


print(sum(mylist))

LINEAR SEARCH:

Given a list of elements and x an element to be searched in the list. Start from the leftmost
element of the list and compare x with each and everyelement in the list. If x matches with an
element in list, return the index else return -1.

Program:
def linearsearch(list, key):
for i in range(len(list)):
if(list[i] == key):
return i
return -1data = []
n = int(input(“Enter the number of elements in the list: ”))for i
in range(0, n):
data.append(input(‘Enter element’))
x = int(input(‘Enter element to be searched’))
found = linearsearch(data, x)
if found != -1:
print(‘Element ’,x,‘ found at position’, found+1)
else:
print(‘Element ’,x,‘ is not in the list’)
BINARY SEARCH:
Binary search is a fast search algorithm. This search works on the principle of divide
and conquer algorithm. The data collection should be in sorted form. The binary search looks
for a particular item by comparing middle item of the data collection. If a match occurs, then
the index of the item is returned. If the middle item is greater than the item, then the item is
searched in the sub-array to the left of the middle. Otherwise, the item is searched for in the
sub-array to the right of the middle item. This process continues onsub-array until the size of
the sub-array reduces to zero.
Example:
Consider the following sorted array and assume to search the location of value 31.

10 14 19 26 27 31 33 35 42 44

0 1 2 3 4 5 6 7 8 9
In this array, start is 0 and end is 9. Calculate mid of the array. Calculate mid by using
formula (start + end) / 2
mid = 0 + 9 / 2 = 9 / 2 = 4.5 ≈ 4

start mid end


↓ ↓ ↓
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Compare 31 with mid element i.e. 27. Since 31 is greater than 27 perform search onrightsub
array.
Now start = mid + 1 = 4 + 1 = 5 end = 9Calculate mid = (start + end) / 2
mid = (5 + 9) / 2
mid = 14 / 2 = 7
start mid end
↓ ↓ ↓

10 14 19 26 27 31 33 35 42 44

0 1 2 3 4 5 6 7 8 9
Compare 31 with mid element i.e. 35. Since 31 is less than 35 perform search on leftsub-
array
Now end = mid - 1 = 7 - 1 = 6 start = 5Calculate mid = (start + end) / 2
mid = (5 + 6) / 2
mid = 11 / 2 = 5.5 ≈ 5

start, end
mid ↓

10 14 19 26 27 31 33 35 42 44

0 1 2 3 4 5 6 7 8 9
Compare 31 with mid element i.e. 31. Since they are equal return the index.
Program:

def bin(sortedlist, n, x):


start = 0 end = n-1
while(start <= end):
mid = (start + end) / 2 if(x ==
sortedlist[mid]):
return mid
elif(x < sortedlist[mid]):
end = mid – 1else:
start = mid + 1return -1
n = int(input(‘Enter the no. of elements: ’))sortedlist = []
for i in range(n):
sortedlist.append(input(‘Enter %dth element: ’%i))x =
input(‘Enter the no. to be searched: ’)
pos = bin(sortedlist, n, x)if(pos != -1):
print(‘Element present’) else
print(‘Element not present’)
1. LIST

1.What is a list? (2 MARKS) (JAN 2018)


3.How list differs from tuple. (2 MARKS) (JAN 2018)
4.How to slice a list in Python. (2 MARKS) (NOV 2018)
2.Relate String and List? (2 MARKS) (JAN 2019)
5. How to create a list in python? Illustrate the use of negative indexing of list with example.
(8 MARKS) (MAY 2019)
6.How will you update list items? Give one example. (8 MARKS) (DEC 2019)
7.Explain in detail about lists, list operations and list slices. (8 MARKS) (JAN 2019)
8.In python how the values stored in list are accessed? Should the elements of a list be of a same
datatype. (2 MARKS) (JAN 2022)

LIST:

 List is an ordered sequence of items. Values in the list are called elements / items.
 It can be written as a list of comma-separated items (values) between square
brackets[ ].
 Items in the lists can be of different data types.
a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]

 The following list contains a string, a float, an integer, and another list
['spam', 2.0, 5, [10, 20]]
 A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
 As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
Operations Examples Description
Create a list >>> a=[2,3,4,5,6,7,8,9,10] In this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a
10 last element
using negative indexing.
>>> print(a[0:3])
[2, 3, 4] Printing a part of the list.
Slicing >>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>b=[20,30] Adding and
Concatenation >>> print(a+b) printing the items
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, of two lists.
30]
Repetition >>> print(b*3) Create a multiple copies of
[20, 30, 20, 30, 20, 30] the same list.
>>> print(a[2]) Updating the list using
Updating 4 index value.
>>> a[2]=100
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10] Returns True if element is
>>> 5 in a present in list. Otherwise
Membership True returns false.
>>> 100 in a
False
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elements
Comparison >>>b=[2,3,4] in both elements are same.
>>> a==b Otherwise returns false
False
>>> a!=b
True

LIST SLICES:
List slicing is an operation that extracts a subset of elements from an list and
packagesthem as another list.
 default start value is 0
 default stop value is n-1
 [:] this will print the entire list
 [2:2] this will create a empty slice
 Syntax:
Listname[start:stop]
Listname[start:stop:steps]

Slices Example Description


a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from0 to 2.
>>> a[0:3]
[9, 8, 7]

a[:4] >>> a[:4] Default start value is 0. so


[9, 8, 7, 6] prints from 0 to 3

a[1:] >>> a[1:] default stop value will be


[8, 7, 6, 5, 4] n-1. so prints from 1 to 5

a[:] >>> a[:] Prints the entire list.


[9, 8, 7, 6, 5, 4]

a[2:2] >>> a[2:2][ ] print an empty slice

a[0:6:2] >>> a=[9,8,7,6,5,4] Slicing list values with step


>>> a[0:6:2] size 2.(from index[0] to 2nd element and
[9, 7, 5]
from that position to next 2nd element
>>> a[0:6:3]
[9,6]

LIST METHODS:
Syntax:
List name.methodname(element/list/index)
Python provides methods that operate on lists.
Syntax Example Description
>>> a=[1,2,3,4,5] Add an element tothe end of
a.append(element) >>> a.append(6) the list
>>> print(a) [1, 2, 3, 4, 5, 6]
a.insert(index,element) >>> a.insert(0,0) Insert an item at the
>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]
a.extend(b) >>> a=[1,2,3,4,5] Add all elements of alist to
>>> b=[7,8,9] the another list
>>> a.extend(b)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
>>>a=[0, 1, 2, 3, 8,5, 6, 7, Returns the index of
a.index(element) 8,9] the first matcheditem
>>> a.index(8)4
>>> a=[1,2,3,4,5] Sort items in a list in
sum() >>> sum(a) ascending order
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
>>> a.reverse() Reverse the order ofitems in
a.reverse() >>> print(a) the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop() Removes and returns an
>>>a=[8,7,6,5,4,3,2,1,0]
>>> a.pop() element at the last element
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1]
a.pop(index) >>> a.pop(0) Remove the particular
8 element
>>>print(a) and return it.
[7, 6, 5, 4, 3, 2, 1, 0]
>>>a=[7, 6, 5, 4, 3, 2, 1] Removes an item
a.remove(element) >>> a.remove(1) from the list
>>> print(a)
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6] Returns the count of number
a.count(element) >>> a.count(6) of items passed as an
2 argument
>>>a=[7, 6, 5, 4, 3, 2] Returns a
a.copy() >>> b=a.copy() copy of the list
>>> print(b)
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2] Return the length of
len(list) >>> len(a) the length
6
>>>a=[7, 6, 5, 4, 3, 2] Return the sum of
sum(list) >>> sum(a) element in a list
27
max(list) >>> max(a) Return the maximum
7 element in a list.
a.clear() >>> a.clear() Removes all items
>>> print(a)[ from the list.
]
del(a) >>> del(a) Delete the entire list.
>>> print(a)
Error: name 'a' is not
Defined

LIST LOOPS:
 For loop
 While loop
 Infinite loop

1) List using For Loop:


 The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last item in the sequence.
 The body of for loop is separated from the rest of the code using indentation.
Syntax:
for val in sequence:
Accessing element Output
a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index Output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range Output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
2) List using While loop:

 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
 When the condition is tested and the result is false, the loop body will be skipped
and the first statement after the while loop will be executed.
 Syntax:
while (condition):
body of while

Sum of elements in list Output


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

3) Infinite Loop:
 A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.

Example Output
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

MUTABILITY:
 Lists are mutable. (can be changed)
 Mutability is the ability for certain types of data to be changed without entirely
recreating it.
 An item can be changed in a list by accessing it directly as part of the assignment
statement.
 Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.
Example Description

changing single element


>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing multiple element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]

ALIASING(COPYING):

 Creating a copy of a list is called aliasing.


 When you create a copy both the list will be having same memory location.changes
in one list will affect another list.
 Alaising refers to having different names for same list values.

Example Output
a= [1, 2, 3 ,4 ,5] [1, 2, 3, 4, 5]
b=a True
print (b) [100,2,3,4,5]
a is b [100,2,3,4,5]
a[0]=100
print(a)
print(b)
 In this a single list object is created and modified using the subscript operator.
 When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.
 This type of change is what is known as a side effect. This happens because after the
assignment b=a, the variables a and b refer to the exact same list object.
 They are aliases for the same object. This phenomenon is known as aliasing.
 To prevent aliasing, a new object can be created and the contents of the original can
be copied which is called cloning.
CLONNING:

 To avoid the disadvantages of copying we are using cloning.


 Creating a copy of a same list of elements with two different memory locations is
called cloning.
 Changes in one list will not affect locations of another list.
 Cloning is a process of making a copy of the list without modifying the original list.
Slicing
list()method
copy() method
1)Clonning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b) [1,2,3,4,5]
>>>a is b
False #because they have different memory location
2) Clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b) [1,2,3,4,5]
>>>a is b false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
2) Clonning using copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b False
LIST AS PARAMETERS:

 In python, arguments are passed by reference.


 If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.
 When a list to a function is passed, the function gets a reference to the list.
 Passing a list as an argument actually passes a reference to the list, not a copy of the
list.
 Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.

Example Output

def remove(a): [2,3,4,5]


a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)

def inside(a): inside [11, 12, 13, 14, 15]


for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)

def insert(a): [30, 1, 2, 3, 4, 5]


a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
2. TUPLE
1.What is tuple in python? How does it differ from list? (2 MARKS) (N0V 2019)
2.Write separate python program to illustrate create, access, concatenate and delete
operations in a tuple. (8 MARKS)(JAN 2022)

TUPLE:

 A tuple is same as list, except that the set of elements is enclosed in parentheses
insteadof square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
 But tuple can be converted into list and list can be converted in to tuple.
Methods Example Description
list( ) >>> a=(1,2,3,4,5) It Convert The Given
>>> a=list(a) Tuple Into List.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] It Convert The Given List
>>> a=tuple(a) Into Tuple.
>>> print(a)
(1, 2, 3, 4, 5)

Benefits of Tuple:
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.
 Tuples are faster than lists.
Operations:
Operations Examples Description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different
data types.
>>>print(a[0]) Accessing the item
Indexing 20 in the position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) Repeating the tuple in n
>>>(2,4,2,4) no of times
>>> a=(2,3,4,5,6,7,8,9,10) Returns True if element
>>> 5 in is present in tuple.
Membership a True Otherwise returns false.
>>> 100 in
a False
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10) Returns True if all
Comparison >>>b=(2,3,4) elements in both
>>> a==b elements are same.
Otherwise returns false
False
>>> a!=b
True

Tuple Methods:
Tuple is immutable so changes cannot be done on the elements of a tuple once it is
assigned.

Methods Example Description


a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple

max(tuple) >>> max(a) return the maximum


5 element in a tuple

del(tuple) >>> del(a) Delete the entire tuple.


TUPLE ASSIGNMENT:

 Tuple assignment allows, variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.
 Multiple assignment works by creating a tuple of expressions from the right hand side,
and a tuple of targets from the left, and then matching each expression to a target.
 Because multiple assignments use tuples to work, it is often termed tuple assignment.
 It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments:

 Multiple values can be assigned to multiple variables using tuple assignment.


>>>(a,b,c)=(1,2,3)
>>>print(a) 1
>>>print(b) 2
>>>print(c) 3
Tuple as return value:

 A Tuple is a comma separated sequence of items.


 It is created with or without ( ).
 A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value

Example Output
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Tuple as
argumet:

 The
par
am
ete
r
na
me
tha
t
beg
ins
wit
h*
gat
her
s
arg
um
ent
int
oa
tup
le.
Example Output
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy