Pps Final Notes
Pps Final Notes
4.1 LISTS
4.2 LIST PARAMETERS
4.3 TUPLES
4.4 TUPLE AS RETURN VALUE
4.5 DICTIONARIES
4.6 ADVANCED LIST PROCESSING
UNIT V: FILES, MODULES, PACKAGES
The programming language Python was conceived in the late 1980s, and
its implementation was started in December 1989 by Guido van
Rossum at CWI in the Netherlands as a successor to ABC capable
of exception handling and interfacing with the Amoeba operating system.
Van Rossum is Python's principal author, and his continuing central role
in deciding the direction of Python is reflected in the title given to him by
the Python community, Benevolent Dictator for Life (BDFL).Python was
named after the BBC TV show Monty Python's Flying Circus.
Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The
structure of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So,
there is no need to compile a program before executing it. You can
simply run the program.
Extensible: Programmers can embed python within their C, C++,
JavaScript, ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code,
and edit it.
High Level Language: When writing programs, programmers
concentrate on solutions of the current problem, no need to worry
about the low level details.
Scalable: Python provides a better structure and support for large programs
than shell scripting.
Powerful: Built-in types and tools, Library utilities, Third party utilities (e.g.
Numeric, NumPy, SciPy)
And Automatic memory management
Applications:
Bit Torrent file sharing
Google search engine, YouTube
Intel, Cisco, HP,IBM
i–Robot
NASA
Face book, Drop box
The following are the primary factors to use python in day-to-day life:
o Python is object-oriented
Structure supports such concepts as polymorphism, operation
overloading and multiple inheritance.
o Indentation
Indentation is one of the greatest feature in python
It’s free (open source)
Downloading python and installing python is free and easy
o It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
o It’s Portable
Python runs virtually every major platform used today
As long as you have a compatible python interpreter installed,
python programs will run in exactly the same manner, irrespective of
platform.
o It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate
form called byte code, which the interpreter then reads.
This gives python the development speed of an interpreter without
the performance loss inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
o Interpreted Language
Python is processed at runtime by python Interpreter
Interactive Programming Language
Users can interact with the python interpreter directly for writing the
programs
o Straight forward syntax
The formation of python syntax is simple and straight forward which
also makes it popular.
Installation:
There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the
python software from http://python.org/downloads/
1.2 ALGORITHMS
What is algorithm?
An algorithm is a finite number of clearly described, unambiguous ―”doable”
steps that can be systematically followed to produce a desired result for given input in
a finite amount of time . Algorithms are the initial stage of problem solving. Algorithms
can be simply stated as a sequence of actions or computation methods to be done for
solving a particular problem. An algorithm should eventually terminate and used to
solve general problems and not specific problems.
State:
Transition from one process to another process under specified condition with
in a time is called state.
Control flow:
The process of executing the individual statements in a given order is called
control flow.The control can be executed in three ways
1. sequence
2. selection
3. iteration
It has been proven that any algorithm can be constructed from just three basic
building blocks. These three building blocks are Sequence, Selection, and Iteration
(Repetition).
Sequence
This describes a sequence of actions that a program carries out one after another,
unconditionally. Execute a list of statements in order. Consider an example,
Step Step
1: Start
1: Start
Step Step
2: READ num1,
2: READ num2num2
num1,
Step Step
3: temp = num1
3: temp = num1
Step Step
4: num1 = num2
4: num1 = num2 S
Step Step
5: num2 = temp
5: num2 = temp
Step Step 6: PRINT
6: PRINT num1,
num1, num2num2
Step Step 7: Stop
7: Stop
SELECTION:
Control flow statements are able to make decisions based on the conditions.
Selection is the program construct that allows a program to choose between
different actions. Choose at most one action from several alternative conditions.
Entr
y
Action 1 Action 2
The decision statements are:
● if
● if/else
● switch
Marks Grade
Above 75 O
60-75 A
50-60 B
40-50 C
Less than 40 D
Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : IF A==B
Print “Equal”
ELSE
Print “ Not Equal”
Strep 5 : Stop
1.4 ITERATION
While Statement:
The WHILE construct is used to specify a loop with a test at the top. The beginning
and ending of the loop are indicated by two keywords WHILE and ENDWHILE.
The general form is:
WHILE condition
Sequence
END WHILE
FOR loop:
This loop is a specialized construct for iterating a specific number of times,
often called a “counting” loop. Two keywords, FOR and ENDFOR are used.
The general form is:
FOR iteration bounds
Sequence
END FOR
Repetition (loop) may be defined as a smaller program the can be executed several
times in a main program. Repeat a block of statements while a condition is true.
Example 1.10 Algorithm for Washing Dishes
Step1: Stack dishes by sink.
Step 2: Fill sink with hot soapy water.
Step 3: While moreDishes
Step 4: Get dish from counter,Wash dish
Step 5: Put dish in drain rack.
Step 6: End While
Step 7: Wipe off counter.
Step 8: Rinse out sink.
Example 1.11 Algorithm to calculate factorial no:
Step1: Start
Step 2: Read the number num.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step4 through 6 until I is equal to num
Step 5: fact = fact * i
Step 6: i = i+1
Step 7: Print fact
Step 8: Stop
1.5 RECURSION
Recursion is a technique of solving a problem by breaking it down into smaller
and smaller sub problems until you get to a small enough problem that it can be easily
solved. Usually, recursion involves a function calling itself until a specified a specified
condition is met.
Example 1.14 Algorithm for factorial using recursion
Step 1 : Start
Step 2 : Input number as n
Step 3 : Call factorial(n)
Step 4 : End
Factorial(n)
Step 1 : Set f=1
Step 2: IF n==1 then return 1
ELSE
Set f=n*factorial(n-1)
Step 3 : print f
Functions:
Functions allow us to conceive of our program as a bunch of sub-steps. When
any program seems too hard, just break the overall program into sub-steps! They allow
us to reuse code instead of rewriting it. Every programming language lets you create
blocks of code that, when called, perform tasks. All programming functions have input
and output. The function contains instructions used to create the output from its input.
The general form of a function definition has return type, parameter list, function
name and function body.
def function_name( parameter list ):
body of the function
return [expression]
Algorithm
Output List
Algorithms can be expressed in many kinds of notation, including
Pseudocod
e
Flowchar
t
Programmin
g
Language
1.6.1 Pseudocode
Pseudo code consists of short, readable and formally styled English languages
used for explain an algorithm.
● It does not include details like variable declaration, subroutines.
● It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not based on
any programming language.
● It gives us the sketch of the program before actual coding.
● It is not a machine readable
● Pseudo code can’t be compiled and executed.
Advantages:
get n
i=1
no
yes
is
i <=
n
stop print i
i=i+1
Recursions:
● A function that calls itself is known as recursion.
● Recursion is a process by which a function calls itself repeatedly until some
specified condition has been satisfied.
Example 1.22 Algorithm for factorial of n numbers using recursion:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Star factorial(
t n)
Get
n
Yes
if(n =
1) fact =
call 1
factorial(n) N
o
fact = return
Print n*factorial(n-1) fact
fact
Sto
p
Example 1.23 Pseudo code for factorial using recursion:
Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
Sub function factorial(n):
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
TWO MARKS QUESTION AND ANSWERS
1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous
do able steps that can be systematically followed to produce a
desired results for given input in the given amount of time. In other
word, an algorithm is a step-by-step procedure to solve a problem
with finite number of steps.
Algorithm Program
1. Systematic logical approach It is exact code written
which is a well-defined, step-by- for problem following all the
step procedure that allows a rules of the programming
computer to solve a problem. language.
2. An algorithm is a finite number The program will accept the
of clearly described, data to perform computation.
unambiguous do able steps that
can be systematically followed Program=Algorithm + Data
to produce a desired results for
given input in the given amount
of time.
Python interpreters
Python interpreters are available for many operating systems, allowing Python
code to run on a wide variety of systems.
>>> bytecod
Bytecod Virtual Progra
or
Prompt e
e Machin m
.py
Sc
Compli e Output
.pyc
Module impo
rt
Two Parts
1. Python byte code compiler
The byte code compiler accepts human readable python expressions and
statements as input and produces machine readable python code as output.
2. A virtual Machine which executes python byte code.
The virtual machine accepts Python byte code as input. And executes the virtual
machine instructions represented by the byte code.
2.2 PYTHON MODES
1. Interactive mode
Interactive Mode, as the name suggests, allows us to interact with OS. Here,
when we type Python statement, interpreter displays the result(s) immediately. That
means, when we type Python expression / statement / command after the prompt (>>>),
the Python immediately responses with the output of it.
The three right arrows are the expression prompt. The prompt is telling you that
the Python system is waiting for you to type an expression. The window in which the
output is displayed and input is gathered is termed the console.
Let’s see what will happen when we type print “WELCOME TO PYTHON
PROGRAMMING” after the prompt.
>>>print “WELCOME TO PYTHON PROGRAMMING”
WELCOME TO PYTHON PROGRAMMING
Example:
>>> print 5+10
15
>>> x=10
>>>y=20
>>> print x*y
200
Almost all Python expressions are typed on a single line. An exception to this rule
occurs when expressions are typed in parenthesis. Each opening parenthesis must be
matched to a closing parenthesis.
If the closing parenthesis is not found, a continuation prompt is given. Normally this
continuation prompt looks like an ellipsis, that is, three dots.
(2 +...
The continuation prompt is telling you that there is more to the expression you
need to type. Fill in the rest of the expression, hit return, and the expression will be
evaluated as before:
>>> (2+
……..3)
>>>5
2. Script Mode
In script mode, we type Python program in a file and then use interpreter to
execute the content of the file. Working in interactive mode is convenient for beginners
and for testing small pieces of code, as one can test them immediately.
But for coding of more than few lines, we should always save our code so that it
can be modified and reused.
Python, in interactive mode, is good enough to learn, experiment or explore, but
its only drawback is that we cannot save the statements and have to retype all the
statements once again to re-run them.
Example: Input any two numbers and to find Quotient and Remainder.
Code:
a = input (“Enter first number”)
b = input (“Enter second number”)
print “Quotient”, a/b
print “Remainder”, a%b
Enter first number10
Enter second number3
Quotient 3
Data Types
Boolean
It is a set of values, and the allowable operations on those values. It can be one
of the following:
1. Python Numbers:
Number data types store numeric values. Number objects are created when you
assign a value to them.
For example
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement.
The syntax of the del statement is
del var1[,var2[,var3[......,varN]]]]
You can delete a single object or multiple objects by using the del statement.
For example
del var
del var_a, var_b
Python supports four different numerical types
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers
Python allows you to use a lowercase l with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1. Python displays
long integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
The built in numeric types supports the following operations:
2.Boolean
A Boolean value is either true or false. It is named after the British mathematician,
George Boole, who first formulated Boolean algebra.
In Python, the two Boolean values are True and False (the capitalization must be
exactly as shown), and the Python type is bool.
>>> type(True)
<class ‘bool‘>
>>> type(true)
Traceback (most recent call last):
File “<interactive input>”, line 1, in <module>
NameError: name ‘true‘ is not defined
Example:
>>> 5 == (3 + 2) # Is five equal 5 to the result of 3 + 2?
True
>>> 5 == 6
False
>>> j = “hel”
>>> j + “lo” == “hello”
True
3. String
A String in Python consists of a series or sequence of characters - letters, numbers,
and special characters.
Strings are marked by quotes:
● single quotes (‘ ‘)
Eg, ‘This a string in single quotes’
● double quotes (“ “)
Eg, “‘This a string in double quotes’”
● triple quotes(“”” “””)
Eg, This is a paragraph. It is made up of multiple lines and sentences.”””
● Individual character in a string is accessed using a subscript (index).
● Characters can be accessed using indexing and slicing operations
Example
Output
Hello World!
H
lo
llo World!
Hello World!Hello World!
Hello World!TEST
Strings in Python can be enclosed in either single quotes (‘) or double quotes
(“), or three of each ( ‘ or “””)
>>>type(‘This is a string.‘) <class ‘str‘>
>>> type(“And so is this.”)
<class ‘str‘>
>>>type(“””and this.”””)
<class ‘str‘>
>>>type(‘‘‘and even this...‘‘‘)
<class ‘str‘>
Double quoted strings can contain single quotes inside them.
(“Alice‘s Cup”)
Single quoted strings can contain double quotes inside them
(‘Alice said ,”Hello”’)
Strings enclosed with three occurrences of either quote symbol are called triple
quoted strings. They can contain either single or double quotes:
>>>print(‘‘‘“Oh no”, she exclaimed, “Ben‘s bike is broken!”‘‘‘) “Oh no”,
she exclaimed, “Ben‘s bike is broken!”
>>>Triple quoted strings can even span multiple lines:
>>>message = “””This message will
... span several
... lines.”””
>>>print(message)
This message will span several lines.
4. Lists
List is also a sequence of values of any type. Values in the list are called elements
/Items. These are mutable and indexed/ordered. List is enclosed in square
brackets ([]).
Example
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]
tinylist = [123, ‘john’]
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Output
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003]
abcd
[786, 2.23]
[2.23, ‘john’, 70.200000000000003]
[123, ‘john’, 123, ‘john’]
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’]
5. Variable
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value.
The assignment statement creates new variables and gives them values:
>>> message = “What’s up, Doc?”
>>> n = 17
>>> pi = 3.14159
This example makes three assignments. The first assigns the string “What’s up,
Doc?” to a new variable named message. The second gives the integer 17 to n, and the
third gives the floating-point number 3.14159 to pi.
The print statement also works with variables.
>>> print message What’s up, Doc?
>>> print n
17
>>> print pi
3.14159
The type of a variable is the type of the value it refers to.
>>> type(message) <type ‘str’>
>>> type(n)
<type ‘int’>
>>> type(pi)
<type ‘float’>
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example “
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to multiple
variables.
For example “
a,b,c = 1,2,”john”
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value “john” is assigned to the variable c.
6. Keywords
Keywords define the language ‘s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords:
Output:
Area is 10
Perimeter is 14
Statements
A statement is an instruction that the Python interpreter can execute. We have
seen two kinds of statements: print and assignment. When you type a statement on the
command line, Python executes it and displays the result, if there is one. The result of
a print statement is a value. Assignment statements don‘t produce a result. A script
usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
Example
print 1
x=2
print x
It produces the following output
1
2
8. Tuple Assignment
Tuples are a sequence of values of any type and are indexed by integers. They
are immutable. Tuples are enclosed in ().
Example
Output
‘Bob‘
>>>age
19
>>>studies
‘CS’
Swapping in tuple assignment:
(a, b) = (b, a)
The left side is a tuple of variables; the right side is a tuple of values. Each value
is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments.
Naturally, the number of variables on the left and the number of values on the
right have to be the same:
>>> (a, b, c, d) = (1, 2, 3)
Value Error: need more than 3 values to unpack
2.4 PRECEDENCE OF OPERATORS
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
Order of operations
When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence. Python follows the same precedence rules for its
mathematical operators that mathematics does. The acronym PEMDAS is a useful
way to remember the order of operations:
1. Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in parentheses
are evaluated first, 2 * (3–1) is 4, and (1+1)**(5–2) is 8. You can also use
parentheses to make an expression easier to read, as in (minute * 100) / 60,
even though it doesn‘t change the result.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and
3*1**3 is 3 and not 27.
3. Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3–1 yields
5 rather than 4, and 2/3-1 is -1, not 1 (remember that in integer division, 2/3=0).
4. Operators with the same precedence are evaluated from left to right. So in the
expression minute*100/60, the multiplication happens first, yielding 5900/60,
which in turn yields 98. If the operations had been evaluated from right to left,
the result would have been 59*1, which is 59, which is wrong.
• Operators
Types of Operators:
– Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Arithmetic operators in Python
Examples
a=10
b=5
print(“a+b=”,a+b)
print(“a-b=”,a-b)
print(“a*b=”,a*b)
print(“a/b=”,a/b)
print(“a%b=”,a%b)
print(“a//b=”,a//b)
print(“a**b=”,a**b)
Output
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000
• and b=5.
Example
a=10
b=5
print(“a>b=>”,a>b)
print(“a>b=>”,a<b)
print(“a==b=>”,a==b)
print(“a!=b=>”,a!=b)
print(“a>=b=>”,a<=b)
print(“a>=b=>”,a>=b)
Output:
a>b=> True
a>b=> False
a==b=> False a!
=b=> True
a>=b=> False
a>=b=> True
2.5 ASSIGNMENT OPERATORS
Assignment Operator combines the effect of arithmetic and assignment operator
Example
a = 21
b = 10
c=0
c=a+b
print(“Line 1 - Value of c is “, c) c += a
print(“Line 2 - Value of c is “, c) c *= a
print(“Line 3 - Value of c is “, c) c /= a
print(“Line 4 - Value of c is “, c) c = 2
c %= a
print(“Line 5 - Value of c is “, c) c **= a
print(“Line 6 - Value of c is “, c) c //= a
print(“Line 7 - Value of c is “, c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators
Symbol Description
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
not Reverses the state of operand/condition.
Example
a = True
b = False
print(‘a and b is’,a and b)
print(‘a or b is’,a or b)
print(‘not a is’,not a)
Output
x and y is False
x or y is True
not x is False
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual
Operator Description Example
& Binary Operator copies a bit to the result (a & b) (means 0000 1100)
AND if it exists in both operands
| Binary OR It copies a bit if it exists in either (a | b) = 61 (means 0011 1101)
operand.
^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49 (means 0011 0001)
operand but not both.
~ Binary Ones It is unary and has the effect of (~a ) = -61 (means 1100 0011
Complement ‘flipping’ bits. in 2’s complement form due to
a signed binary number.
<< Binary The left operands value is moved a << 2 = 240 (means 1111
Left Shift left by the number of bits specified 0000)
by the right operand.
>> Binary The left operands value is moved a >> 2 = 15 (means 0000 1111)
Right Shift right by the number of bits specified
by the right operand.
Example:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a | b; # 61 = 0011 1101
print “Line 2 - Value of c is “, c
c = a ^ b; # 49 = 0011 0001
print “Line 3 - Value of c is “, c
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Membership Operators:
These operators test whether a value is a member of a sequence. The sequence
may be a list, a string, or a tuple. We have two membership python operators- ‘in’ and
‘not in’.
Operator Description Example
In Evaluates to true if it finds a variable x in y, here in results in a 1 if
in the specified sequence and false x is a member of sequence y.
otherwise.
not in Evaluates to true if it does not finds a x not in y, here not in results
variable in the specified sequence and in a 1 if x is a member of
false otherwise. sequence y.
Example:
a. in
This checks if a value is a member of a sequence. In our example, we see that the
string ‘fox’ does not belong to the list pets. But the string ‘cat’ belongs to it, so it
returns True. Also, the string ‘me’ is a substring to the string ‘disappointment’.
Therefore, it returns true.
>>> pets=[‘dog’,’cat’,’ferret’]
>>> ‘fox’ in pets
False
>>> ‘cat’ in pets
True
>>> ‘me’ in ‘disappointment’
True
b. not in
Unlike ‘in’, ‘not in’ checks if a value is not a member of a sequence.
>>> ‘pot’ not in ‘disappointment’
True
Identity Operator
Let us proceed towards identity Python Operator.
These operators test if the two operands share an identity. We have two identity
operators- ‘is’ and ‘is not’.
a. is
If two operands have the same identity, it returns True. Otherwise, it returns
False. Here, 2 is not the same as 20, so it returns False. Also, ‘2’ and “2” are the same.
The difference in quotes does not make them different. So, it returns True.
>>> 2 is 20
False
>>> ‘2’ is “2”
True
b. is not
2 is a number, and ‘2’ is a string. So, it returns a True to that.
>>> 2 is not ‘2’
True
2.6 COMMENTS
As programs get bigger and more complicated, they get more difficult to read. It
is a good idea to add notes to your programs to explain in natural language what the
program is doing.
A comment in a computer program is text that is intended only for the human
reader — it is completely ignored by the interpreter.
There are two types of comments in python:
Single line comments
Multi line comments
Single Line Comments
In Python, the # token starts a comment..
Example
print(“Not a comment”)
#print(“Am a comment”)
Result
Not a comment
Multiple Line Comments
Multiple line comments are slightly different. Simply use 3 single quotes before
and after the part you want commented.
Example
’’
print(“We are in a comment”)
print (“We are still in a comment”)
’’
print(“We are out of the comment”)
Result
We are out of the comment
ILLUSTRATIVE EXAMPLES
1. Python Program to swap or exchange the values of two variables
Method 1
a = 10
b = 20
print(“before swapping\na=”, a, “ b=”, b)
temp = a
a=b
b = temp
print(“\nafter swapping\na=”, a, “ b=”, b)
Method 2
a = 30
b = 20
print(“\nBefore swap a = %d and b = %d” %(a, b))
a, b = b, a
print(“\nAfter swaping a = %d and b = %d” %(a, b))
2. Circulate the values of n Variables
l=[1,2,3,4,5]
print(l[::-1])
3. Python Program to test the year is leap or not
The engine that translates and runs Python is called the Python Interpreter. It is
available for many OS. Two parts of the interpreter are: (i) Python byte code
compiler (ii) A virtual machine
3. What are the two modes of python?
Interactive mode
Interactive Mode, as the name suggests, allows us to interact with OS. Here,
when we type Python statement, interpreter displays the result(s) immediately.
It acts as a calculator.
In script mode, we type Python program in a file and then use interpreter to
execute the content of the file.
4. Define continuation prompt.
The continuation prompt will notify you that there is more to the expression you
need to
type.
>>> (2 +
... 3) # continuation
5
5. What are application and system programs?
A value is one of the basic things a program works with, like a letter or a number.
These values are classified into different classes, or data types:
1,2 – Integers
‘Hello World‘- String
7. Define identifiers.
Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.
8. What are the rules for declaring the identifiers?
The data type specifies the type of data which can be stored.
10. What is Boolean?
A Boolean value is either true or false. In Python, the two Boolean values are
True and False and the Python type is bool
11. What is the use of type() function?
List is also a sequence of values of any type. Values in the list are called elements
/ items.
These are mutable and indexed/ordered. List is enclosed in square brackets ([]).
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]
14. Define variable.
Keywords define the language‘s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords. Eg: global, or, with, assert,
else, if, pass, yield
17. State the definition of statement.
Tuples are a sequence of values of any type and are indexed by integers. They
are immutable. Tuples are enclosed in (). Eg: tuple = ( ‘abcd’, 786 , 2.23, ‘john’,
70.2 )
19. State the precedence of operators.
The operator precedence rule in python is used to execute the expression contains
more than one operator.
The precedence rule is:
P EMDAS –
1. Parenthesis
2. Exponentiation
3. Multiplication, Division (Same precedence) – If both comes, evaluate
from left to right
4. Addition , Subtraction (Same precedence) – If both comes, evaluate
from left to right
20. What are comments?
A comment in a computer program is text that is intended only for the human
reader
Comments are used for documenting our program.
It is useful in large programs.
It is not printed and ignored by the interpreter.
Types of comments:
Single line comments – Starts with # symbol.
Eg: #print(“Am a comment”)
Multi line comments – Starts and ends with three single quotes.
Eg:
‘’’
print(“We are in a comment”)
print (“We are still in a comment”)
UNIT III
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
Example 3.2:
>>> type(True)
<type ‘bool’>
>>> type(False)
<type ‘bool’>
Capitalization should be exact. Ignoring the proper use of upper or lower case,
will result in error.
Example 3.3:
>>> type(true)
Traceback (most recent call last):
File “<interactive input>, line 1 in <module>,
NameError: name ‘true‘ is not defined
3.1.1 Relational Operators
The relational operators (Comparison Operators) which return the Boolean values
are:
x != y x is not equal to y
x==y x is equal to y
x>y x is greater than y
x<y x is less than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y
Note: A common error is using the mathematical symbol = in the expressions
and it is an assignment operator. There are no operators like => or =<.
3.1.2 Logical Operators
There are three logical operators: and, or, and not. The semantics (meaning)of
these operators is similar to their meaning in English.
Example3.4:
n=88
if n%2 ==0 or n%3==0:
print(“yes”)
O
u
t
p
u
t
:
yes
Program 2:
n=6
if n%2==0 or n%3==0:
print(“yes”)
O
u
t
p
u
t
:
yes
The not operator negates a boolean expression, so not (x > y) is True if x > y is
False, that is, if x is less than or equal to y.
The expression on the left of the or operator is evaluated first: if the result is
True, Python does not evaluate the expression on the right — this is called short-
circuit evaluation.
Similarly, for the ―and operator, if the expression on the left yields False, Python
does not evaluate the expression on the right. So there are no unnecessary evaluations.
Python is not very strict. Any nonzero number is interpreted as True:
>>> 42 and True
True
Recommended online video tutorial link: Boolean values and operators
https://www.youtube.com/watch?v=xgzdb2hTdL0
condition condition
True False
True False
loop
if <test_expression>:
<body>
Test Fals
Expressio e
n
Tru
e
Body of
if
Compound statements
if x < 0:
pass
if grade>=70:
print ( First class‘)
3.2.1.1 if-else Statement (Alternative)
The if..else statement evaluates test expression and will execute body of if only
when test condition is True. If the condition is False, body of else is executed.
Indentation is used to separate the blocks.
The syntax of ‘if..else’ statement:
if test condition:
Body of if
else:
Body of else
Test Fals
Expressio e
n
Tru
e
if x % 2 == 0:
print(‘x is even’)
else:
print(‘x is odd’)
If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays an appropriate message. If the condition is false, the second set of
statements runs. Since the condition must be true or false, exactly one of the alternatives
will run. The alternatives are called branches, because they are branches in the flow of
execution.
3.2.1.2 Chained Conditionals (IF-ELIF-ELSE Statement)
● Sometimes there are more than two possibilities and we need more than
two branches.
● The elif is short for else if. It allows us to check for multiple expressions.
● If the condition for if is False, it checks the condition of the next elif block
and so on.
● If all the conditions are False, body of else is executed.
● Only one block among the several if...elif...else blocks is executed according
to the condition.
● The if block can have only one else block. But it can have multiple elif
blocks.
The syntax of ‘if..elif..else’ statement:
if condition:
Body of if
elif condition:
Body of elif
else:
Body of else
Test Fals
Expressio e
n of if
Tru
e Test Fals
Expressio e
Body of n of elif
if
Tru
e
Body of Body of
elif else
Example 1:
if x < y:
print(‘x is less than y’)
elif x > y:
print(‘x is greater than y’)
else:
print(‘x and y are equal’)
elif is an abbreviation of ―else if . Again, exactly one branch will run. There is
no limit on the number of elif statements. If there is an else clause, it has to be at the
end, but there doesn‘t have to be one.
Example 2:
if choice == ‘a’:
draw_a()
elif choice == ‘b’:
draw_b()
elif choice == ‘c’:
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and
so on. If one of them is true, the corresponding branch runs and the statement ends.
3.3 ITERATION
Iteration is repeating a set of instructions and controlling their execution for a
particular number of times. Iteration statements are also called as loops.
3.3.1 State
A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7. Python
uses the equal sign (=) for assignment. First, equality is a symmetric relationship and
assignment is not.
For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a
= 7 is legal and 7 = a is not. Also, in mathematics, a proposition of equality is either
true or false for all time. If a =b now, then a will always equal b. In Python, an
assignment statement can make two variables equal.
>>> a=5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5
The third line changes the value of ―a but does not change the value of ―b , so
they are no longer equal. A common kind of reassignment is an update, where the
new value of the variable depends on the old.
>>> x = x + 1
This means ―get the current value of x, add one, and then update x with the
new value. If we try to update a variable that doesn‘t exist, you get an error, because
Python evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name ‘x’ is not defined, Before you can update a variable, you have
to initialize it, usually with a simple assignment:
>>>x = 0
>>>x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a
decrement.
while n > 0:
print(n)
n=n–1
The above while statement prints the value of n a number of times until n is
greater than zero.
The flow of execution for a while statement:
Enter while
loop
Test Fals
Expressio e
Tru
e
Body
of
while
Exit
loop
The body of the loop should change the value of one or more variables so that
the condition becomes false eventually and the loop terminates. Otherwise the loop
will repeat forever, which is called an infinite loop. In the case of countdown, we can
prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise,
n gets smaller each time through the loop, so eventually we have to get to 0. For some
other loops, it is not so easy to tell.
Example: Python while Loop
We can have an optional else block with while loop as well. The else part is
executed if the condition in the while loop evaluates to False. The while loop can be
terminated with a break statement. In such case, the else part is ignored. Hence, a
while loop’s else part runs if no break occurs and the condition is false.
Example
# Program to illustrate the use of else statement with the while loop
counter = 0
while counter < 3:
print(“Inside loop”)
counter = counter + 1
else:
print(“Inside else”)
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times. On the
forth iteration, the condition in while becomes False. Hence, the else part is executed.
3.3.3 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. The for loops are
used to construct definite loops.
Syntax of FOR LOOP:
Yes
Las
t
N
o
Body of for
Exit
loop
Fig: operation of for loop
Apple
Banana
Pear
The range() function:
sum = 0
for k in range(1, 11):
sum = sum + k
The values in the generated sequence include the starting value, up to but not
including the ending value. For example, range(1, 11) generates the sequence [1, 2, 3,
4, 5, 6, 7, 8,9, 10].
The range function is convenient when long sequences of integers are needed.
Actually, range does not create a sequence of integers. It creates a generator function
able to produce each next item of the sequence when needed.
for i in range(4):
print(‘Hello!’)
for loop with else
A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts. break statement can be used to
stop a for loop. In such case, the else part is ignored. Hence, a for loop’s else part runs
if no break occurs.
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print(“No items left.”)
Output:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the else and prints No items left.
3.3.4 Break
Break statement is used to break the loop. For example, suppose you want to
take input from the user until they type done.
Enter
loop
test Fals
expressio e
n of loop
Tru
e
Yes
break
?
N
Exit loop
o
Remaining
body of
loop
Fig 3.7 Flowchart of Break
s
t
r
n
g
The end
This program is same as the above example except the break statement has been
replaced with continue. We continue with the loop, if the string is “i”, not executing
the rest of the block. Hence, we see in our output that all the letters except “i” gets
printed.
Enter
loop
Fals
test e
expressio
n of loop
Tru
e
Yes
continue
?
N
Exit loop
o
Remaining
body of
loop
3.3.6 Pass
It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing happens
when it executes. The pass is also useful in places where your code will eventually
go, but has not been written yet.
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.
Example:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Difference between various iterations Pass Continue Break
Pass
● Indefinite Loops
The exit condition will be evaluated again, and execution resumes from the
top.
For
● Definite Loop
The item being iterated over will move to its next element.
3.4 FRUITFUL FUNCTIONS
Think about this version and convince yourself it works the same as the first
one. Code that appears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through
the program hits a return statement. The following version of absolute value fails to
do this:
def absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x
Write a function that takes two points, the center of the circle and a point on the
perimeter, and computes the area of the circle. Assume that the center point is stored
in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to
find the radius of the circle, which is the distance between the two points.
radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it. Again
we will useone of our earlier functions:
result = area(radius)
return result
#Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
We called this function area2 to distinguish it from the area function defined
earlier. The temporary variables radius and result are useful for development,
debugging, and single-stepping through the code to inspect what is happening, but once
the program is working, we can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
3.4.4 Recursion
Recursion is the process of calling the function that is currently executing. It is
legal for one function to call another; it is also legal for a function to call itself. An
example of recursive function to find the factorial of an integer.
Example:
0! = 1
n! = n(n - 1)!
This definition says that the factorial of 0 is 1, and the factorial of any other
value, n, is n multiplied by the factorial of n - 1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together,
3! equals 3 times 2 times 1 times 1, which is 6.
The flow of execution for this program is similar to the flow of countdown. If
we call factorial with the value 3:
● Since 3 is not 0, we take the second branch and calculate the factorial of n-1...
● Since 2 is not 0, we take the second branch and calculate the factorial of n-1...
● Since 1 is not 0, we take the second branch and calculate the factorial of n-1...
● Since 0 equals 0, we take the first branch and return 1 without making any
more recursive calls.
● The return value, 1, is multiplied by n, which is 1, and the result is returned.
● The return value, 1, is multiplied by n, which is 2, and the result is returned.
● The return value (2) is multiplied by n, which is 3, and the result, 6, becomes
the return value of the function call that started the whole process.
● The return values are shown being passed back up the stack. In each frame,
the return value is the value of result, which is the product of n and recurse.
In the last frame, the local variables recurse and result do not exist, because
the branch that creates them does not run.
main
6
factorial n 3 recurse 2 result 6
2
factorial
n 2 recurse 1 result 2 1
factorial
1
factorial n 1 recurse 1 result 1
Example:
n 0
# An example of a recursive function to find the factorial of a number
def factorial(x):
“””This is a recursive functionto find the factorial of an integer”””
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print(“The factorial of”, num, “is”, factorial(num))
Output:
The factorial of 3 is 6
A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
>>> fruit = ‘banana’
letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to
letter. The expression in brackets is called an index. The index indicates which
character in the sequence you want (hence the name).But you might not get what
you expect:
>>> letter
‘a’
For most people, the first letter of ‘banana’ is b, not a. But for computer scientists,
the index is an offset from the beginning of the string, and the offset of the first letter
is zero.
>>> letter = fruit[0]
>>> letter
‘b’
So b is the 0th letter (―zero-eth ) of ‘banana’, a is the 1th letter (―one-eth ),
and n is the 2th letter (―two-eth ). As an index you can use an expression that contains
variables and operators:
>>> i=1
>>> fruit[i]
‘a’
But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers
3.5.1 String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:
>>> s = ‘Monty Python’
>>> s[0:5]
‘Monty’
>>> s[6:12]
‘Python’
The operator [n:m] returns the part of the string from the ―n-eth character to
the ―m-eth character, including the first but excluding the last. This behavior is
counter intuitive, butit might help to imagine the indices pointing between the
characters. If you omit the first index (before the colon), the slice starts at the beginning
of the string.
If you omit the second index, the slice goes to the end of the string:
>>> fruit = ‘banana’
>>> fruit[:3]
‘ban’
>>> fruit[3:]
‘ana’
If the first index is greater than or equal to the second the result is an empty
string, represented by two quotation marks:
>>> fruit = ‘banana’
>>> fruit[3:3]
‘’
An empty string contains no characters and has length 0, but other than that, it is
the same as any other string.
3.5.2 Immutability
It is tempting to use the [] operator on the left side of an assignment, with the
intention of changing a character in a string.
For example:
The len function, when applied to a string, returns the number of characters in a
string:
>>> fruit = “banana”
>>> len(fruit)
6
The index starts counting form zero. In the above string, the index value in from
0 to 5.
To get the last character, we have to subtract 1 from the length of fruit:
size = len(fruit)
last = fruit[size-1]
Alternatively, we can use negative indices, which count backward from the end
of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last,
and so on.
3.5.3 String methods
The find method can find character and sub strings in a string.
>>> word = ‘banana’
>>> index = word.find(‘a’)
>>> index
1
>>> word.find(‘na’)
2
By default, find starts at the beginning of the string, but it can take a second
argument, the index where it should start:
>>> word.find(‘na’, 3)
4
This is an example of an optional argument; find can also take a third argument,
the index where it should stop:
>>> name = ‘bob’
>>> name.find(‘b’, 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2, not
including 2.
Split Method:
One of the most useful methods on strings is the split method: it splits a single
multi-word string into a list of individual words, removing all the whitespace between
them. The input string can be read as a single string, and will be split.
>>> ss = “Well I never did said Alice”
>>> wds = ss.split()
>>> wds
[‘Well‘, ‘I‘, ‘never‘, ‘did‘, ‘said‘, ‘Alice‘]
String format method
The easiest and most powerful way to format a string in Python 3 is to use the
format method.
Program:
word = ‘banana’
count = 0
for letter in word:
if letter == ‘a’:
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter.
The variable count is initialized to 0 and then incremented each time an a is found.
When the loop exits, count contains the result—the total number of a‘s.
import string
text = “Monty Python’s Flying Circus”
print “upper”, “=>”, string.upper(text)
print “lower”, “=>”, string.lower(text)
print “split”, “=>”, string.split(text)
print “join”, “=>”, string.join(string.split(text), “+”)
print “replace”, “=>”, string.replace(text, “Python”, “Java”)
print “find”, “=>”, string.find(text, “Python”), string.find(text, “Java”)
print “count”, “=>”, string.count(text, “n”)
upper => MONTY PYTHON’S FLYING CIRCUS
lower => monty python’s flying circus
split => [‘Monty’, “Python’s”, ‘Flying’, ‘Circus’]
join => Monty+Python’s+Flying+Circus replace => Monty Java’s Flying Circus
find => 6 -1
count => 3
String Example Program:
x = array([3, 6, 9, 12])
x/3.0x
print(x)
Output:
array([1, 2, 3, 4])
Example 2:
y = [3, 6, 9, 12]
y/3.0
print(y)
The program will result in the error.Arithmetic calculations – can be done
in array.
Storing data efficiently – Array
def exp(m,n):
return m**n
i=input(“Enter the base:”)
j=input(“Enter the pow:”)
d=exp(i,j)
print d
Output:
list = [4, 2, 8, 9, 3, 7]
x= int(input(“Enter number to search: )) found = False
for i in range(len(list)):
if(list[i] == x):
found = True
print(“%d found at %dth position”%(x,i))
break
if(found == False):
print(“%d is not in list”%x)
Output:
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print(sum)
O
u
t
p
u
t
:
15
2MARKS QUESTION AND ANSWERS
1. What are the two Boolean values in python
A Boolean value is either True or False.
Python type – bool.
2. What is an operator?
The range function is generator and able to produce next item of the sequence
when needed.
It is used in a for loop.
Eg: for val in values: print(val)
7. Differentiate break and continue statement with example
The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
Break statement is used to break the loop.
Eg:
It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing
happens when it executes.
Eg:
Code that ppears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
def absolute_value(x):
if x < 0:
return -x
return x
10. What refers to local and global scope?
Local scope refers to identifiers declared within a function. These identifiers are
kept in the namespace that belongs to the function, and each function has its
own namespace.
Global scope refers to all the identifiers declared within the current module, or
file.
Built-in scope refers to all the identifiers built into Python
11. Which function is called composition?
The function which calls itself again and again is called recursion.
Eg:
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
13. What is a srting? Mention that how do we represent a string in python?
def exp(m,n):
return m**n
i=input(“Enter the base:”)
j=input(“Enter the pow:”)
d=exp(i,j)
print d
18. Define fruitful functions.
Listname[start:stop]
Listname[start:stop:steps]
Example :
List_name.method_name( element/index/list)
Syntax example description
a.append(element) >>> a=[1,2,3,4,5] Add an element to the end of the
>>> a.append(6) list
>>> print(a)
[1, 2, 3, 4, 5,
6]
a.insert(index,element) >>> a.insert(0,0) Insert an item at the defined
>>> print(a) index
[0, 1, 2, 3, 4, 5, 6]
a.extend(b) >>> b=[7,8,9] Add all elements of a list to the
>>> a.extend(b) another list
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
a.index(element) >>> a.index(8) Returns the index of the first
8 matched item
a.sort() >>> a.sort() Sort items in a list in ascending
>>> print(a) order
[0, 1, 2, 3, 4, 5, 6, 7, 8]
a.reverse() >>> a.reverse() Reverse the order of items in the
>>> print(a) list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop() >>> a.pop() Removes and returns an
0 element at the last element
a.pop(index) >>> a.pop(0) Remove the particular element
8 and return it.
a.remove(element) >>> a.remove(1) Removes an item from the list
>>> print(a)
[7, 6, 5, 4, 3, 2]
a.count(element) >>> a.count(6) Returns the count of number of
1 items passed as an argument
a.copy() >>> b=a.copy() Returns a shallow copy of the
>>> print(b) list
[7, 6, 5, 4, 3, 2]
len(list) >>> len(a) Return the length of the length
6
min(list) >>> min(a) Return the minimum element in
2 a list
max(list) >>> max(a) Return the maximum element in
7 a list.
append():
Example 1:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.append(‘goat’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, ‘goat’]
Example 2:
animal = [‘cat’, ‘dog’, ‘rabbit’]
wild_animal = [‘tiger’, ‘fox’]
animal.append(wild_animal)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, [‘tiger’, ‘fox’]]
insert():
Example:
vowel = [‘a’, ‘e’, ‘i’, ‘u’]
vowel.insert(3, ‘o’)
print(‘Updated List: ‘, vowel)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
extend():
Example:
language = [‘French’, ‘English’, ‘German’]
language1 = [‘Spanish’, ‘Portuguese’]
language.extend(language1)
print(‘Language List: ‘, language)
Output:
Language List: [‘French’, ‘English’, ‘German’, ‘Spanish’, ‘Portuguese’]
Index():
Example 1:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘i’, ‘u’]
index = vowels.index(‘e’)
print(‘The index of e:’, index)
index = vowels.index(‘i’)
print(‘The index of i:’, index)
Output:
The index of e: 1
The index of e: 2
Example 2:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
index = vowels.index(‘p’)
print(‘The index of p:’, index)
Output:
ValueError: ‘p’ is not in list
remove():
Example:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.remove(‘rabbit’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’]
clear():
Example:
list = [{1, 2}, (‘a’), [‘1.1’, ‘2.2’]]
list.clear()
print(‘List:’, list)
Output: List: []
Sort():
Example 1:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
vowels.sort()
print(‘Sorted list:’, vowels)
Output:
Sorted list: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example 2:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
vowels.sort(reverse=True)
print(‘Sorted list (in Descending):’, vowels)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
reverse():
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
os.reverse()
print(‘Updated List:’, os)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
reversed_list = os[::-1]
print(‘Updated List:’, reversed_list)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Pop():
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
return_value = language.pop(3)
print(‘Return Value: ‘, return_value)
print(‘Updated List: ‘, language)
Output:
A for statement is an iterative control statement that iterates once for each element
in a specified sequence of elements. Thus, for loops are used to construct definite
loops.
Syntax:
a=[10,20,30,40,50]
for i in a:
print(i)
Output :
1
2
3
4
5
Example 2 :
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(i)
Output :
0
1
2
3
4
Example 3 :
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
Output ;
10
20
30
40
50
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
Example : Sum of Elements in a List
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
4.1.5 List Mutability
Lists are mutable. When the bracket operator appears on the left side of an
assignment, it Identifies the element of the list that will be assigned.
Example:
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
The elements from a list can also be removed by assigning the empty list to
them.
>>> a=[1,2,3,4,5]
>>> a[0:3]=[ ]
>>> print(a)
[4, 5]
The elements can be inserted into a list by squeezing them into an empty
slice at the desired location.
>>> a=[1,2,3,4,5]
>>> a[0:0]=[20,30,45]
>>> print(a)
[20,30,45,1, 2, 3, 4, 5]
4.1.6 List Aliasing
Creating a copy of a list is called aliasing. When you create a copy both list will
be having same memory location. Changes in one list will affect another list. Aliasing
refers to having different names for same list values.
Example :
a= [10,20,30,40]
b=a
print (b)
a is b
b[2]=35 10 20 30 40
print(a) a
a = [10, 20, 30]
print(b) 0 1 2
3
Output :
[10,20,30,40]
b
True
[10,20,30,40] 0
3
1 2
0 1 2 3
0 1 2
b [2] = 35 3
10 20 30 40
a
0 1 2 3
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.
4.1.7 List Cloning
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.
1. Slicing
2. list()method
3. copy() method
Cloning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
Cloning 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]
Cloning using copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b) [1, 2, 3, 4, 5]
>>> a is b
False
4.2 List 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.
Example1 :
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output:
[2,3,4,5]
Example 2:
def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Output
[30, 1, 2, 3, 4, 5]
Suggested links to Refer :
List :
https://www.tutorialspoint.com/videotutorials/
video_course_view.php?course=python_online_training&chapter=python_basic_list_operation
List Using for Loop:
https://www.youtube.com/watch?v=YT6ldZuBW4Y
Python List functions:
https://www.youtube.com/watch?v=96Wr1OO-4d8
Python Slicing: https://www.youtube.com/watch?
v=iD6a0G8MnjA
4.3 TUPLES
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a
tuple is defined, it cannot be altered. Otherwise, tuples and lists are essentially the
same. To distinguish tuples from lists, tuples are denoted by parentheses instead of
square brackets.
Benefit of Tuple:
>>>a=(20,40,60,”apple”,”ball”)
Indexing
>>>print(a[0])
20
>>> a[2]
60
Slicing
>>>print(a[1:3])
(40,60)
Concatenation
>>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”apple”,”ball”,2,4)
Repetition
>>>print(b*2)
>>>(2,4,2,4)
Membership
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
>>> 100 in a
False
>>> 2 not in a
False
Comparison
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4)
>>> a==b
False
>>> a!=b
True
4.3.2 Tuple methods
Tuple is immutable so changes cannot be done on the elements of a tuple once it
is assigned.
a.index(tuple)
>>> a=(1,2,3,4,5)
>>> a.index(5)
4
a.count(tuple)
>>>a=(1,2,3,4,5)
>>> a.count(3)
1
len(tuple)
>>> len(a)
5
min(tuple)
>>> min(a)
1
max(tuple)
>>> max(a)
5
del(tuple)
>>> del(a)
4.3.3 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.
Uses of Tuple assignment:
a=20
b=50
(a,b)=(b,a)
print(“value after swapping is”,a,b)
Multiple assignments:
Example1: 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)
Example2: Output:
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)
4.4.1 Tuple as argument
The parameter name that begins with * gathers argument into a tuple.
Example:
def printall(*args):
print(args)
printall(2,3,’a’)
Output :
(2, 3, ‘a’)
Suggested Links to Refer
Tuples : https://www.youtube.com/watch?v=R8mOaSIHT8U
Tuple as Paramerter : https://www.youtube.com/watch?v=sgnP62EXUtA
Tuple assignment : https://www.youtube.com/watch?v=AhSW1sEOzWY
4.5 DICTIONARIES
A dictionary organizes information by association, not position.
Example: when you use a dictionary to look up the definition of “mammal,”
you don t start at page 1; instead, you turn directly to the words beginning with “M.”
Phone books, address books, encyclopedias, and other reference sources also organize
information by association. In Python, a dictionary associates a set of keys with data
values. A Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries. The entire sequence of entries is
enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Note : Elements in Dictionaries are accessed via keys and not by their position.
Here are some example dictionaries:
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
Output:
dict[‘Name’]: Zara
dict[‘Age’]: 7
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error. We can even create an empty dictionary—that is, a dictionary that
contains no entries. We would create an empty dictionary in a program that builds a
dictionary from scratch.
Dictionary Operations
Operations on dictionary:
4.4.1.1 Accessing an element
4.4.1.2 Update
4.4.1.3 Add element
4.4.1.4 Membership
Creating a dictionary
>>> a={1:”one”,2:”two”}
>>> print(a)
{1: ‘one’, 2: ‘two’}
Accessing an element
>>> a[1]
‘one’
>>> a[0]
KeyError: 0
Update
>>> a[1]=”ONE”
>>> print(a)
{1: ‘ONE’, 2: ‘two’}
Add element
>>> a[3]=”three”
>>> print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’}
Membership
[2, 4, 6, 8]
Example 3 :
[4, 5, 6]
Example 4 :
[0, 1, 4, 9, 16]
2. Nested list:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
ILLUSTRATIVE PROGRAMS
1. Program for matrix addition
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
2. Program for matrix subtraction
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]
for r in result:
print(r)
TWO MARKS QUESTION AND ANSWERS
The list is written as a sequence of data values separated by commas. There are
several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]): ps = [10, 20, 30, 40]
2. Write the different ways to create the list.
List1=[4,5,6].
List2=[]
List2[0]=4
List2[1]=5
List2[2]=6
3. Give an example for nest list
List elements can be changed once after initializing the list. This is called as
mutability.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers[42, 5]
10. Write difference between list aliasing and cloning.
An object with more than one reference has more than one name, the object is
aliased. If the aliased object is mutable, changes made with one alias affect the
other. Clone changes are not being affected the other copy of list.
11. How tuple is differ from list?
A function can only return one value, but if the value is a tuple, the effect is the
same as returning multiple values.
>>> t = divmod(7, 3)
>>> t (2,1)
13. What is a dictionary? Give an example.
Get, fromkeys, clear, copy, items, pop,popitem, setdefault, update, etc. How do
we done the membership test in dictionary?
>>>C={1:1,2:2}
>>>2 in C True
15. Write a python program for iterating the dictionary elements.
2. Binary file
Module Description
r Read only
w mode Write
a only Appending
r+ Read and write only
File Operation:
Open a file
Reading a file
Writing a file
Closing a file
1. Open ( ) function:
Example: 1
fp=open(“a.txt”,”w”)
fp.write(“this file is
a.txt”) fp.write(“to add
more lines”) fp.close()
Example: 2
Splitting line in a text line:
fp=open(“a.txt”,”w) for
line in fp:
words=line.split( )
print(words)
Example:3
Python program to implement File handling operations – create, open, read and write a text
file
f=open('stud.txt','w')
str=input('Enter the file contents:')
f.write(str)
f=open('stud.txt','r')
str=f.read()
print('The file contents are:',str)
f=open('stud.txt','a')
str=input('new the file contents to append:')
f.write(str)
print("file content appended")
f.close()
OUTPUT:
SCREENSHOTS:
Stud.txt file
The file contents are: cat mango hello cat cat
Example:4
Python program to perform copy operation from one file to another file
import shutil
print("Give file name that already exists")
sfile = input("Enter Source File's Name: ")
tfile = input("Enter Target File's Name: ")
shutil.copyfile(sfile, tfile)
print("File successfully copied")
OUTPUT:
Give file name that already exists
Enter Source File's Name: stud.txt
Enter Target File's Name: s1.txt
File successfully copied
Sourcefile – stud.txt
Targetfile – s1.txt
File Operations and Methods :
5.2. FORMAT OPERATOR
The argument of write( ) has to be a string, so if we want to put other values in a file, we have to
convert them to strings.
The first operand is the format string, which specifies how the second operand is formatted.
The result is a string. For example, the format sequence '%d' means that the second
operand should be formatted as an integer (d stands for decimal ):
Example 1:
x=10
print('value =% i', %x)
Output will be:
Value = 10
Example 2:
name= 'Manivel'
Example 3:
num=123.456123
Example 4:
num =123.456123
The command line argument is used to pass input from the command line to your program
when they are started to execute.
Handling command line arguments with Python need sys module.
sys module provides information about constants, functions and methods of the pyhton
interpreter.
argv[ ] is used to access the command line argument. The argument list starts from 0.
argv[ ] the first argument always the file name
sys.argv[0]= gives file name
sys.argv[1]=provides access to the first input
Example 1 output
import sys python demo.py
print( the file name is %s %(sys.argv[0])) the file name is demo.py
To run a Python program, we execute the following command in the command prompt terminal of the
operating system.
For example, in windows, the following command is entered in Windows command prompt terminal.
Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3 are command
line arguments for the program.
If the program needs to accept input from the user, Python's input() function is used. When the
program is executed from command line, user input is accepted from the command terminal.
Errors
Error is a mistake in python also referred as bugs .they are almost always
the fault of the programmer.
The process of finding and eliminating errors is called debugging
Types of errors
o Syntax error or compile time error
o Run time error
o Logical error
Syntax errors
Syntax errors are the errors which are displayed when the programmer do
mistakes when writing a program, when a program has syntax errors it
will not get executed
Leaving out a keyword
Leaving out a symbol, such as colon, comma, brackets
Misspelling a keyword
Incorrect indentation
Runtime errors
If a program is syntactically correct-that is ,free of syntax errors-it will
be run by the python interpreter
However, the program may exit unexpectedly during execution if it
encounters a runtime error.
When a program has runtime error it will get executed but it will not produce output
Division by zero
Performing an operation on incompatible types
Using an identifier which has not been defined
Trying to access a file which doesn’t exit
Logical errors
Logical errors are the most difficult to fix
They occur when the program runs without crashing but produces incorrect result
Using the wrong variable name
Indenting a blocks to the wrong level
Using integer division instead of floating point division
Getting operator precedence wrong
Exception handling
Exceptions
An exception is an error that happens during execution of a program. When
that Error occurs
Errors in python
S.No. Exception Name Description
1 FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for
2
all numeric types.
1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally
Example:
try:
result = X / ( X – Y )
print(“result=”.result)
except ZeroDivisionError:
print(“Division by Zero”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of y”))
try:
sum = X +
Y divide =
X/Y
print (“ Sum of %d and %d = %d”, %(X,Y,sum))
print (“ Division of %d and %d = %d”, %(X,Y,divide))
except NameError:
print(“ The input must be number”)
except ZeroDivisionError:
print(“Division by Zero”)
3. Try –Except-Else
o The else part will be executed only if the try block does not raise the exception.
o Python will try to process all the statements inside try block. If value
error occur, the flow of control will immediately pass to the except
block and remaining statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
Example
X=int(input(“Enter the value
of X”)) Y=int(input(“Enter the
value of Y”)) try:
result = X / ( X – Y )
except ZeroDivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
4. Raise statement
The raise statement allows the programmer to force a specified exception to occur.
Example:
>>> raise
NameError('HiThere')
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
If you need to determine whether an exception was raised but don’t intend
to handle it, a simpler form of the raise statement allows you to re-raise
the exception:
Example
try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
...
raise
Outp
ut:
An exception flew by!
Traceback (most recent call
last):
File "<stdin>", line 2, in
<module> NameError: HiThere
5. Try –Except-Finally
Syntax
try:
statements
except:
statements
finally:
statements
Example:
Built-in Exceptions
Raised when the built-in function for a data type has the
ValueError
15 valid type of arguments, but the arguments have invalid
values specified.
RuntimeError Raised when a generated error does not fall into any
16
category.
Output:
The result is 7
The result is
8.2 The result
is ab
The result is
yonaalex Welcome,
fleming
4. from……import statement:
5.OS Module
import os
6. Sys Module
import sys
Methods example description
sys.argv sys.argv Provides the list of
command line arguments
passed to a python script
sys.argv(0) Provides to access the
file name
sys.argv(1) Provides to access the first
input
sys.path sys.path It provide the search path
for module
sys.path.append() sys.path.append() Provide the access to
specific path to our
program
sys.platform sys.platform Provide information
‘win32’ about the operating
system
platform
sys.exit sys.exit Exit from python
<built.in function exit>
i.e add(),sub(),mul(),div()
Output :
>>> 15
5
50
2
NumPy
NumPy stands for Numerical Python, is an open-source Python library that provides
support for large, multi-dimensional arrays and matrices. NumPy is the fundamental package for
scientific computing in Python. It also have a collection of high-level mathematical functions to
operate on arrays. It was created by Travis Oliphant in 2005.
What is NumPy?
NumPy is a general-purpose array-processing package.
It provides a high-performance multidimensional array object and tools for working with
these arrays.
It is the fundamental package for scientific computing with Python. It is open-source
software.
Features of NumPy
NumPy has various features which make them popular over lists.
Numpy can be installed for Mac and Linux users via the following pip command:
Arrays in NumPy
It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers.
NumPy’s array class is called ndarray. It is also known by the alias array.
Simple Example :
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],[ 4, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)
OUTPUT:
Files are collection of data. It is stored in computer memory and can be taken
any time we require it. Each file is identified by a unique name. In general a text
file is a file that contains printable characters and whitespace, organized into
lines separated by newline characters.
Eg: file.txt
2. List the two methods used for installing python pacakage.
The pip install script is available within our scientific Python installation.
python setup.py install
Variables defined inside a module are called attributes of the module. Attributes
are accessed using the dot operator (.)
6. Define namespaces in python.
import random
rng = random.Random()
dice_throw = rng.randrange(1,7)
8. What is called exception?
Exception is an event , which occurs during the execution of program and distrupts
the normal flow of programs instructions.
9. What are the two ways to handle the exceptions.
if a<5
File “<interactive input>”, line 1
if a < 5
^
SyntaxError: invalid syntax
11. Describe about the command line arguments.
A format sequence can appear anywhere in the string,so we can embed a value
in a sentence: print(‘In %d years I have spotted %g %s.’ % (3, 0.1, ‘camels’))
‘{} {}’.format(1,2)
12
13. Write a program to write a data in a file.
Eg:
f = open(“pec.dat”,”w”)
f.write(“Welcome to PEC”)
f.close()
Eg:
Text=f.read()
Print text
TWO MARKS QUESTION AND ANSWERS
Read Write
A "Read" operation occurs when a A "Write" operation occurs when a
computer program reads information computer program adds new information, or
from a computer file/table (e.g. to be changes existing information in a computer
displayed on a screen). file/table.
The "read" operation
gets information out of
a file.
After a "read", the information from the After a "write", the information from the
file/table is available to the computer file/table is available to the computer
program but none of the information that program but the information that was read
was read from the file/table is changed in from the file/table can be changed in any
any way. way.
Error is a mistake in python also referred as bugs . they are almost always the
fault of the programmer.
The process of finding and eliminating errors is called debugging
Types of errors
Syntax error or compile time error
Run time error
Logical error
Exceptions
An exception is an error that happens during execution of a program. When that Error occurs
Syntax:
try :
statements
except :
statements
7. Write a program to add some content to existing file without effecting the existing content.
file=open(“newfile.txt”,a)
file.write(“hello”)
9. What is module?
A python module is a file that consists of python definition and statements. A module can define
functions, classes and variables. It allows us to logically arrange related code and makes the code easier to
understand and use
Output:
C:\\Users\\Mano\\Desktop
Import os
os.path.abspath('w rite.py')
Output:
'C:\\Users\\Mano\\Desktop\\write.py'
NumPy is the fundamental package for scientific computing in Python. NumPy is a general-purpose
array-processing package. It provides a high-performance multidimensional array object and tools for
working with these arrays. It is the fundamental package for scientific computing with Python. It is
open-source software.