UNIT 1 PDS Notes
UNIT 1 PDS Notes
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.
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
INTRODUCTION TO PYTHON:
Uses:
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:
PYTHON INTERPRETER:
PYTHON IS 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
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.
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.
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,
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.
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.
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:
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.
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:
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.
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.
1. Syntax errors
2. Runtime errors
3. Semantic errors.
1) SYNTAX ERRORS:
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.
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:
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
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:
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:
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.
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’>
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:
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.
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:
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.
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
EXPRESSIONS:
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:
COMMENTS:
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
OPERATORS:
ARITHMETIC 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
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
ASSIGNMENT OPERATORS:
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
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.
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:
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
Python supports one unary arithmetic operators. Unary (-) minus – operator yields
the negation of its numeric argument
Example:
a = 10
print(-a)
-10
Operator precedence:
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:
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.
Example:
(3-9) / 3 + 77 * (3-1)
-6 / 3 + 77 * 2
-2 + 154
152
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.
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
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:
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
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)
OUTPUT:
Enter first value : 10
Enter second value : 20
After Swapping
First value : 20
Second value : 10
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.
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))
# 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
Method 2:
To find the distance between 2 points, given by the coordinates (X1,Y1) and
(X2,Y2), the Pythagorean theorem is used.
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
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
Output:
Enter the value for m: 100Enter the value for n: 50
The interchanged value are: 50 , 100
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
Output:
Enter the number: 5Odd number
Enter the number: 26Even number
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
Output:
Enter a number:5
Positive
Enter a number: -4
Negative
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:
ITERATION – LOOPING
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:
Output:
char is: pchar is: ychar is: t char is: hchar is: ochar is: n
Program 2:
Output:
C C++
java python
Program 3:
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
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:
Output:
0
1
2
3
4
5
Output:
Week day: Monday Week day: Tuesday Week day: Wednesday Week day: Thursday Weekday:
Friday Week day: Saturday Week day: Sunday
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
Output:
0
1
2
3
Exit of the loop
Output:
Enter the number: 9243 Reverse
of given number: 3429
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
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
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
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)
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.
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
Output:
Current letter: PCurrent letter: yCurrent letter: t Current letter: oCurrent letter: n
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
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:
Required Arguments:
Example:
def printing(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)
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)
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:
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)
uses:Example:
def print_sample():
print(‘Hi’) print(‘Hello’)
def repeat_print():
print_sample()
print_sample()
repeat_print()
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.
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:
Output:
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:
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:
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
Output:
lambda: 5
lambda within lambda: 8
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]
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()
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:
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.
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
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
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
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 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
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]
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)
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)
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:
Output:
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
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))
Program:
def sum(numlist):
if len(numlis0 == 1:
return numlist[0]
else:
return numlist[0] + sum(numlist[1:])
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
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:
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]
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
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
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
ALIASING(COPYING):
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:
Example Output
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.
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:
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')