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

Python Notes

fdghfdghfgh

Uploaded by

santo nino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python Notes

fdghfdghfgh

Uploaded by

santo nino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 149

ALGORITHMIC PROBLEM SOLVING

PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a correct
program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
1.ALGORITHM

It is defined as a sequence of instructions that describe a method for solving a problem. In other
words it is a step by step procedure for solving a problem

 Should be written in simple English


 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates.

Building Blocks of Algorithm


As algorithm is a part of the blue-print or plan for the computer program. An algorithm is constructed
using following blocks.
 Statements
 States
 Control flow
 Function Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may consists of
assignment statements, input/output statements, comment statements
Example:
 Read the value of ‘a’ //This is input statement
 Calculate c=a+b //This is assignment statement
 Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.
States

An algorithm is deterministic automation for accomplishing a goal which, given an initial state, will terminate in
a defined end-state.
An algorithm will definitely have start state and end state.

Control Flow
Control flow which is also stated as flow of control, determines what section of code is to run in
program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow

Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes, diamonds, and
other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols S.No Name of symbol
1. Terminal
Symbol
Symbol Type Description

1 Oval Represent the start and stop of the.

Input/ Output symbol

2 Parallelogram Denotes either input or output operation.

3. Process symbol Rectangle Denotes the process to be carried

4. Decision symbol Diamond Represents decision making and


branching

5. Flow lines Arrow lines Represents the sequence of steps and


direction of flow. Used to connect
symbols.
6. Connector Circle A connector symbol is represented
by a circle and a letter or digit is
placed in the circle to specify the
link. This symbol is used to
connect flowcharts.

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
2. The flow chart should be clear, neat and easy to follow. There should not be any room for ambiguity
in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
Only one flow line should come out from a process s ol. y
m
b
4. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible
answer, cap leave the decision symbol.

5. Only one flow line is used in conjun ction inalterm


with symbol.

6. If flowchart be come
s complex, it is better to use connector symbols to reduce the number of
flow lines.
7. Ensure that flowchart has logical start and stop.

Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for various purposes.
Efficient Coding
The flowcharts act as a guide or blue print during the system analysis and program development phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part.

Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart becomes
complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re- drawing
completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.

Programming Language
 A programming language is a vocabulary and set of grammatical rules for instructing a computer or
computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
 Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Types of Programming Language
In general Programming languages are classified into three types. They are
 Low – level or Machine Language
 Intermediate or Assembly Language
 High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that
utilize programmable microcode). Machine languages are the only languages understood by computers. It
is also called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
High – level Language:
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that enables a
programmer to write programs that are more or less independent
of a particular type of computer. Such languages are considered high-level because they are closer to
human languages and further from machine languages. Ultimately, programs written in a high-level language
must be translated into machine language by a compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.
Language Type
Interpreted Programming Language
Functional Programming Language
Compiled Programming Language
Procedural Programming Language
Scripting Programming Language
Markup Programming Language
Logical Programming Language
Concurrent Programming Language
Object Oriented Programming Language
Interpreted Programming Language:
Example
Python, BASIC, Lisp

1. INTRODUCTION TO PYTHON:

Python is a general-purpose interpreted, interactive, object-oriented, and high-level


programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the year 2000.

 Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
 Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner- Level
programmers and supports the development of a wide range of applications.
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.

Applications:
Bit Torrent file sharing
Google search engine, YouTube
Intel, Cisco, HP,IBM
i–Robot
NASA
Face book, Drop box
Python interpreter:

Interpreter: To execute a program in a high-level language by translating it one line ata time.
Compiler: To translate a program written in a high-level language into a low-level language all at once, in
preparation for later execution.

Modes of python interpreter:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
 Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s) immediately.
Advantages:
 Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small pieces of code.
Drawback:
 We cannot save the statements and have to retype all the statements once again to re-run them. In
interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If you
type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!') Hello, World! This is an example of a print statement. It displays a result on the
screen. In this case, the result is the words.
Script mode:
In script mode, we type python program in a file and then use interpreter to execute the content of the
file.
Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with.py
Save the code with filename.py and run the interpreter in script mode to execute the script.

Interactive mode
A way of using the Python interpreter by typing commands and expressions at the prompt. Can’t save and edit
the code . we cannot save the statements for further use and we have to retype all the statements to re-run them.

Script mode
A way of using the Python interpreter to read and execute statements in a script. an save and edit the code If we
want to experiment with the code, we can use interactive mode.

Integrated Development Learning Environment(IDLE):


Is a graphical user interface which is completely written in Python.
It is bundled with the default implementation of the python language and also comes with optional
part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting. Auto completion with smart indentation.
Python shell to display output with syntax highlighting.

2.VALUES AND DATATYPES


Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.) Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:

Numbers:
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Python supports integers, floating point numbers and complex numbers. They are defined as,
Sequence:
 A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable (values cannot be changed)
datatypes.  There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
 A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
 Strings are marked by quotes:
 Single quotes(' ') E.g., 'This a string in single quotes'
 double quotes(" ") E.g., "'This a string in double quotes'"
 triple quotes(""" """)E.g., """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 .Strings are
Immutable i.e the contents of the string cannot be changed after it is created.
Indexing:

 Positive indexing helps in accessing the string from the beginning


 Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ven(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
 Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership

Lists
 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 datatypes.

Operations on list: Indexing


Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
Creating a list >>>list1=["python", 7.79, 101,
"hello”]
>>>list2=["god",6.78,9]
Indexing >>>print(list1[0]) python
>>>list1[2]

Tuple:
 A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of 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.
 Benefit of Tuple:
 Tuples are faster than lists.
 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.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101,
"hello”)
Indexing >>>print(t[0]) python
>>>t[2]
101
Dictionaries:

-This data type is unordered and mutable.


-Dictionaries fall under Mappings.  Lists are ordered sets of objects, whereas dictionaries are
unordered sets.
 Dictionary is created by using curly brackets. i,e.{}
 Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated
(or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-
pairs(The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
Creating a dictionary

Data type Compile time Run time


int a=10 a=int(input(“enter a”)) float
a=10.5 a=float(input(“enter a”)) string
a=”panimalar” a=input(“enter a string”) list
a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))
Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And Indentation,
Quotation In Python, Tuple Assignment:

VARIABLES:
 A variable allows us to store a value by assigning it to a name, which can be used later.
 Named memory locations to store values.
 Programmers generally choose names for their variables that are meaningful.
 It can be of any length. No space is allowed.
 We don't need to declare a variable before using it. In Python, we simply assign a value to a variable and
it will exist.

Assigning value to variable:


Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45 print
(counter)

Assigning a single value to several variables simultaneously:

>>> a=b=c=100
Assigning multiple values to multiple variables:

>>>a,b,c=2,4,"ram"

KEYWORDS:
 Keywords are the reserved words in Python.
 We cannot use a keyword as name, function name or any other identifier.
 They are used to define the syntax and structure of the Python language.
 Keywords are case sensitive.
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in Python.
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).  all are valid example.
 An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
 Cannot use special symbols like!, @, #, $, % etc. in our identifier.
 Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

Valid declarations Invalid declarations


Num Number 1
Num num1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no IF
if
Else else

STATEMENTS AND EXPRESSIONS:


Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying avalue.
>>> n = 17
>>>print (n)

Here, 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.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
>>>print(z) hifriend

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Syntax for input() is:

variable = input (“data”) Example:


>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. Conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
>>> print ("Hello")
Hello

COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows:
Example:
# This is a comment.
# This is a comment, too.
# I said that already.

DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method definition. We
must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname doc. Example:
def double(num):
"""Function to double thevalue"""
return2*num
>>>print (double. doc )
Function to double the value

LINES AND INDENTATION:


Most of the programming languages like C, C++, Java use braces { } to define a block of code. But,
python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control. Example:
a=3 b=1
if a>b:
print("a is greater")
else:
print("b is greater")

QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.

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

TUPLE ASSIGNMENT

An assignment to all of the elements in a tuple using a single assignment statement.


Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
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. This feature makes
tuple assignment quite versatile.
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)
ValueError: need more than 3 values to unpack

Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:

Swap two numbers Output:


a=2;b=3
print(a,b) (2, 3)
temp = a (3, 2) a =
b >>>
b = temp print(a,b) -Tuple assignment solves this problem neatly:

(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>>b = ("George",25,"20000") # tuplepacking

-In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on the
right:
>>>b = ("George", 25, "20000")
# tuple packing >>>(name, age, salary)=b # tupleunpacking
>>>name
'George'
>>>age
25
>>>salary
'20000'

-The right side can be any kind of sequence (string, list,tuple)


Example:
-To split an email address in to user name and a domain
>>>mailid='[email protected]'
>>>name,domain=mailid.split('@')
>>>print name god
>>> print (domain) abc.org

4.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
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:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30


- Subtraction Subtracts operand.
right hand operand from left hand a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2


% Modulus Divides left hand operand by right hand operand and returns remainder
b%a=0
** Exponent Performs operators
exponential (power) calculation on a**b =10 to the power 20
// Floor Division - The division of operands where the result is the quotient in which the
digits after the decimal point are removed
5//2=2

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

Comparison (Relational)Operators:
 Comparison operators are used to compare values.
 It either returns True or False according to the condition. Assume, a=10 and b=5

Operator Description Example

== If the values of two operands are equal, then the condition (a


== b) is becomes true. not true.

!= If values of two operands are not equal, then condition becomes true. (a!=b) is true
> If the value of left operand is greater than the value of right operand, then condition becomes true.
(a > b) is not true.
< If the value of left operand is less than the value of right operand, then condition becomes true.
(a < b) is true.
>= If the value of left operand is greater than or equal to the value of right operand, then condition
becomes true.
(a >= b) is not true.
<= If the value of left operand is less than or equal to the value of right operand, then condition
becomes true.
(a <= b) is true.

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

Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands to left side operand c = a + b assigns
value of a + b into c

+= Add AND It adds right operand to the left operand and assign the result to leftoperand
c += a is equivalent to c
=c+a
-= Subtract
AND
It subtracts right operand from the left operand and assign the result to left operand
c -= a is equivalent to c
= c -a *= AND
Multiply It multiplies right operand with the left operand and assign the result to left operand
c *= a is equivalent to c
= c *a
/= AND
Divide It divides left operand with the right operand and assign the result to left operand
c /= a is equivalent to c
= c /ac
/= a is equivalent to c
= c /a

%= AND
Modulus It takes modulus using two operands and assign the result to left operand
c %= a is equivalent to c
=c%a
**= Exponent
AND
Performs exponential (power) calculation on operators and assign value to the left operand
c **= a is equivalent to c
= c ** a
//= Floor
Division
It performs floor division on operators and assign value to the left operand
c //= a is equivalent to c
= c // a

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 is2
Line 6 - Value of c is 2097152
Line 7 - Value of c is99864 Logical Operators:
-Logical operators are the and, or, not operators.

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 bits
Example: Let x = 10 (0000 1010 in binary)and
y = 4 (0000 0100 in binary)

Example
a = 60 # 60 = 0011 1100
Output
Line 1 - Value of c is 12 b = 13 c = 0
c = a & b;
# 13 = 0000 1101

# 12 = 0000 1100
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is-61 print "Line 1 - Value of c is ", c c = a|b; # 61 = 00111101 print "Line 2 - Value
of c is ", c
c = a^b; # 49 = 00110001
print "Line 3 - Value of c is ", c
c =~a; # -61 = 11000011
Line 5 - Value of c is 240
Line 6 - Value of c is 15 print "Line 4 - Value of c is ", c
c = a<<2; # 240 = 11110000 print
"Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111 print
"Line 6 - Value of c is ", c

Membership Operators:

 Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or not.
 Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators areused.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False

Identity Operators:
• They are used to check if two values (or variables) are located on the same partof the
memory.

Example
x =5 y =5
x2 = 'Hello'
y2= 'Hello' print(x1 is not y1) print(x2 is y2)

Output False True


5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators


= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

-For mathematical operators, Python follows mathematical convention.


-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) is a
useful way to remember the rules:
• 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) is8.
• You can also use parentheses to make an expression easier to read,asin(minute
* 100) / 60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and2
*3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4,
and 6+4/2 is 8, not5.
• Operators with the same precedence are evaluated from left to right (except exponentiation). Examples:

a=9-12/3+3*2-1 a=?
a=9-4+3*2-1
a=9-4+6-1 a=5+6-1 a=11-
1 a=10
A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6 A=6+4-
1+6
A=10-1+6
A=9+6 A=15

find m=?
m=-43||8&&0||-2 m=-
43||0||-2 m=1||-2
m=1

FUNCTIONS:
 Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.

Need For Function:


• When the program is too complex and large they are divided into parts. Each part is separately
coded and combined into single program. Each subprogram is called as function.
• Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.

Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a programmer. It cannot be modified.
Built in function Description

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object


>>>range(2,8,1) [2,
3, 4, 5, 6, 7]
#returns range of given values >>>round(7.8) 8.0 #returns rounded integer of the given
number

>>>chr(5)
\x05'
>>>float(5)
5.0
#returns a character (a string) from an integer

#returns float number from string or integer >>>int(5.0) 5 # returns integer from
string or float

>>>pow(3,5) 243 #returns power of given number


>>>type( 5.6)
<type 'float'>
>>>t=tuple([4,6.0,7])
(4, 6.0, 7)
>>>print("good morning")
Good morning
>>>input("enter name:")
enter name : George
#returns data type of object to which it belongs
# to create tuple of items from list

# displays the given object

# reads and returns the given string

ii) User Defined Functions:


• User defined functions are the functions that programmers create for their requirement anduse.
• These functions can then be combined to form module which can be used in other programs by
importing them.
• Advantages of user defined functions:
 Programmers working on large project can divide the workload by making different functions.
 If repeated code occurs in a program, function can be used to include those codes and execute when
needed by calling that function.

Function definition: (Sub program)


• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in which arguments are given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement Syntax:
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]

Example:
def my_add(a,b):
c=a+b
return c

Function Calling: (Main Function)


 Once we have defined a function, we can call it from another function, program or even the
Pythonprompt.
 To call a function we simply type the function name with appropriate arguments.
Example:
x=5 y=4
my_add(x,y)

Flow of Execution:


The order in which statements are executed is called the flow of execution

Execution always begins at the first statement of the program.

Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember that statements
inside the function are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the flow
jumps to the first line of the called function, executes all the statements there, and then comes back to
pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This
means that you will read the def statements as you are scanning from top to bottom, but you should skip the
statements of the function definition until you reach a point where that function is called.

Function Prototypes:

i. Function without arguments and without return type


ii. Function with arguments and without return type iii. Function without arguments and with return
type iv. Function with arguments and with return type i) Function without arguments and without
return type
o In this type no argument is passed through the function call and no output is return to main
function
o The sub function will read the input values perform the operation and print the result in the
same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is return to the main
function.
iv)Function with arguments and with return type
o In this type arguments are passed through the function call and output is return to the main
function
Without Return Type
Without argument With argument
def add():
a=int(input("enter a")) b=int(input("enter b")) c=a+b
print(c)
add()
def add(a,b): c=a+b print(c)
a=int(input("enter a")) b=int(input("enter b")) add(a,b)

OUTPUT: OUTPUT: enter


a5 enter a5 enter b 10
enter b 10
15 15

With return type


Without argument With argument
def add(): def add(a,b): a=int(input("enter a"))
b=int(input("enterb")) c=a+b
return c c=add()
print(c)
c=a+b return c
a=int(input("enter a")) b=int(input("enter b")) c=add(a,b)
print(c)

OUTPUT: OUTPUT: enter


a5 enter a5 enter b 10
enter b 10
15
15 Parameters And Arguments:
Parameters:
 Parameters are the value(s) provided in the parenthesis when we write function header.
 These are the values required by function to work.
 If there is more than one value required, all of them will be listed in parameter list separated by
comma.
 Example: defmy_add(a,b):
Arguments :
 Arguments are the value(s) provided in function call/invoke statement.
 List of arguments should be supplied in same way as parameters are listed.
 Bounding of parameters to arguments is done 1:1, and so there should be same number and type of
arguments as mentioned in parameter list.
 Example:my_add(x,y)
RETURN STATEMENT:
 The return statement is used to exit a function and go back to the place from where it was called.
 If the return statement has no arguments, then it will not return any values. But exits from function.
Syntax:
return[expression]

Example:
def my_add(a,b):
c=a+b return
c x=5
y=4
print(my_add(x,y))
Output:
9

ARGUMENT TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments

Required Arguments :The number of arguments in the function call should match exactly with the
function definition.

defmy_details( name, age ):


print("Name: ", name)
print("Age ", age) return
my_details("george",
56) Output:
Name:
georgeAge56
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with parameters even though
if they are arranged in out of order.

def my_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name:
georgeAge56

DefaultArguments:
Assumes a default value if a value is not provided in the function call for that argument.
defmy_details( name, age=40 ):
print("Name: ", name)
print("Age ", age) return
my_details(name="george")
Output:
Name:
georgeAge40

Variable lengthArguments
If we want to specify more arguments than specified while defining the function, variable length
arguments are used. It is denoted by * symbol before parameter.

def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")

Output:
rajanrahulmichealä rjun

7.MODULES:
 A module is a file containing Python definitions ,functions, statements and instructions.
 Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the module.  Once we import a
module, we can reference or use to any of its functions or variables in our code.
 There is large number of standard modules also available in python.
 Standard modules can be imported the same way as we import our user- defined
modules.
 Every module contains many functions.
 To access one of the function , you have to specify the name of the module and the name of the function
separated by dot .This format is called dot notation. Syntax: import
module_namemodule_name.function_name(variable)
Importing Builtin Module:
import math x=math.sqrt(25)
print(x)

Importing User Defined Module:


import calx=cal.add(5,4)
print(x)
Built-in python modules are,
1.math– mathematical functions:
some of the functions in math module is,
math.ceil(x) - Return the ceiling of x, the smallest integer greater than or equal to x
math. floor(x) - Return the floor of x, the largest integer less than or equal to x. math.
factorial(x)-Return x factorial.
math.gcd(x,y)-Return the greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.pi - The mathematical constant π = 3.141592
math.e – returns The mathematical constant e = 2.718281

2
.random-Generate pseudo-random numbers
random.randrange(stop) random.randrange(start, stop[, step])
random.uniform(a, b)
-Return a random floating point number

CONTROL FLOW, FUNCTIONS


Conditionals: Boolean values and operators, conditional (if), alternative (if-else),chained conditional (if-elif-
else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters,
scope: local and global, composition ,recursion; Strings: string slices, immutability, string functions and
methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum the
array of n\ umbers, linear search, binary search.

1) Conditional Statements

Conditional if

Alternative if… else

Chained if…elif…else
 Nested if….else

Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if will be
executed.
syntax:

Flowchart:

Program to provide bonus mark if the category is output


sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90 Alternative (if-else):
In the alternative the condition must be true or false. In this else statement can be combined with if
statement. The else statement contains the block of code that executes when the condition is false. If the
condition is true statements inside the if get executed otherwise else part gets executed. The alternatives are
called branches, because they are branches in the flow of execution.
syntax:

Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not

Nested conditionals
One conditional can also be nested within another. Any number of condition can be nested inside one
another. In this, if the condition is true it checks another if condition1. If both the conditions are true
statement1 get executed otherwise statement2 get execute. if the condition is false statement3 gets
executed
Syntax

Flowchart:

Example:
1. greatest of three numbers
2. positive negative or zero

2.Iteration Or Control Statements.


 state
 while
 for
 break
 continue
 pass
State:

state.

Transition from one process to another process under specified condition with in a time is called While loop:
While loop statement in Python is used to repeatedly executes set of statement as long as a given
condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if the test
expression is True. After one iteration, the test expression is checked again. This process continues until
the test expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while start with indentation and the first unintended line marks the end.

Syntax:

for in range:
We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.

syntax

Flowchart:
For in sequence
 The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a sequence
is called traversal. Loop continues until we reach the last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.

Sequence can be a list, strings or tuples

s.no sequences example output


R
1. For loop in string for i in "Ramu": A print(i)
MU2
2. For loop in list for i in [2,3,5,6,9]: 3 print(i)
5
6
9

for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1

Examples:
1. Program to print Fibonacci series.
2. check the no is prime or not

71 CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax: Continue
Flowchart

Example: Output
for i in "welcome": w if(i=="c"):
e
continue l print(i)
om
e
PASS


It is used when a statement is required syntactically but you don’t want any code to execute.

It is a null statement, nothing happens when it is executed.

72 Syntax: pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e pass
l print(i) co
m
e

Difference between break and continue

break continue

It terminates the current loop and It terminates the current iteration and executes
the remaining statement outside transfer the control to the next iteration in the loop.
the loop.

syntax: syntax:
break continue

for i in "welcome": for i in "welcome":


if(i=="c"): if(i=="c"):
break continue print(i)
print(i)

w we
e
l lom
e

else statement in loops:

else in for loop:




If else statement is used in for loop, the else statement is executed when the loop has reached the limit.
The statements inside for loop and statements inside else will also execute.

example output
for i in range(1,6): 1
print(i) 2 else:
3 print("the number greater than 6") 4
5 the number greater than 6

else in while loop:


If else statement is used within while loop , the else part will be executed when the condition become
false.
The statements inside for loop and statements inside else will also execute.
Program output i=1
1 while(i<=5): 2
print(i) 3 i=i+1
4 else: 5
print("the number greater than 5") the number greater than 5
Fruitful Function


Fruitful function

Void function

Return values

Parameters

Local and global scope

Function composition
 Recursion

A function that returns a value is called fruitful function.


Example:
Root=sqrt (25)
Example:
def add(): a=10 b=20
c=a+b return
c
c=add()
print(c) Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add(): a=10
b=20
c=a+b
print(c)
add()

Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable return
a,b– return 2 variables return
a+b– return expression return 8–
return value
nd
PARAMETERS / ARGUMENTS(refer 2 unit)

Local and Global Scope

Global Scope

The scope of a variable refers to the places that you can see or access a variable.

A variable with global scope can be used anywhere in the program.

It can be created by defining a variable outside the function.
Example output
a=50
def add()

Global Variable

b=20 70
c=a+b
print©
Local Variable

def sub():
b=30
c=a-b 20
print©
print(a) 50

Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20

c=a+b 70

Local Variable
print©
def sub():
b=30 20
c=a-b

Local Variable
print©
print(a) error print(b)
error

Function Composition:

Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as the argument of the
next function.
In other words the output of one function is given as the input of another function is known as
function composition.

find sum and average using function output


composition
def sum(a,b): enter a:4 sum=a+b
enter b:8 return sum the avg is
6.0
def avg(sum):
avg=sum/2 return
avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b) avg=avg(sum)
print("the avg is",avg)

Recursion
A function calling itself till it reaches the base value - stop point of function call. Example:
factorial of a given number using recursion

Factorial of n Output
def fact(n): enter no. to find fact:5 if(n==1):
Fact is 120
return 1 else:
return n*fact(n-1)

n=eval(input("enter no. to find fact:"))


fact=fact(n)
print("Fact is",fact)
Explanation

Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10 if(n==1):
Fact is 55
return 1 else:
return n*sum(n-1)

n=eval(input("enter no. to find sum: "))

sum=sum(n)
print("Fact is",sum)

Explain about Strings and its operation:


String is defined as sequence of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative). A index
starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created. Python
will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

>>>a=”HELLO” Positive indexing helps in accessing


indexing >>>print(a[0]) the string from the beginning

>>>H Negative subscript helps in accessing


>>>print(a[-1]) the string from the end.
>>>O

Print[0:4] – HELL The Slice[start : stop] operator extracts


Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
>>>print(a+b) Save earth
a=”panimalar ” The * operator repeats the string on the
Repetitions:
>>>print(3*a)
left hand side
times the
value on right
hand side.

panimalarpanimalar
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
Returns true if present
True
>>> "a" not in s
True

String slices:

A part of a string is called string slices.
 The process of extracting a sub string from a string is called slicing.
Print[0:4] – HELL The Slice[n : m] operator extracts sub Slicing:
Print[ :3] – HEL string from the strings.
a=”HELLO” Print[0: ]- HELLO A segment of a string is called a slice.

Immutability:

Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a
print(a)
is not defined string built in functions and methods:
A method is a function that “belongs to” an object.
Syntax to access the method

Stringname.method()

a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False
consists of
alphabetic characters
only. String modules:

A module is a file containing Python definitions, functions, statements.

Standard library of Python is extended as modules.

To use these modules in a program, programmer needs to import the module.

Once we import a module, we can reference or use to any of its functions or variables in our code.

There is large number of standard modules also available in python.

Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,- y
birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567

Escape sequences in string


Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"") (")
"
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”) 6) Array:

Array is a collection of similar elements. Elements in the array can be accessed by index. Index starts
with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example: a=array.array(‘i’,[1,2,3,4]) a-
array name
array- module name i- integer
datatype

Example
Program to find sum of Output
array elements

import array 10 sum=0


a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like a array.

Syntax:
arrayname.fromlist(list_name)

Example
program to convert list Output into
array

import array 35 sum=0


l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i print(sum) Methods of an array

a=[2,3,4,5]

Syntax example Description

1 array(data type, array(‘i’,[2,3,4,5]) This function is used to create value list)


an array with data type and
value list specified in its arguments.

2 append() >>>a.append(6) This method is used to add the


[2,3,4,5,6] at the end of the array.

3 insert(index,element >>>a.insert(2,10) This method is used to add the


) [2,3,10,5,6] value at the position specified in its
argument.

4 pop(index) >>>a.pop(1) This function removes the


[2,10,5,6] element at the position mentioned
in its argument, and
returns it.

5 index(element) >>>a.index(2) This function returns the index


0 of value

6 reverse() >>>a.reverse() This function reverses the


[6,5,10,2] array.
7 count() a.count() This is used to count number of 7.ILLUSTRATIVE
PROGRAMS:

Square root using newtons method: Output:


def newtonsqrt(n): enter number to find Sqrt: 9 root=n/2
3.0
for i in range(10):
root=(root+n/root)/2 print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output n1=int(input("Enter a
number1:")) Enter a number1:8 n2=int(input("Enter a
number2:")) Enter a number2:24 for i in range(1,n1+1):
8
if(n1%i==0 and n2%i==0):
gcd=i print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: ")) exp=int(input("Enter
exponential value:")) result=power(base,exp)
print("Result:",result)
sum of array elements: output: a=[2,3,4,5,6,7,8]
the sum is 35 sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output a=[20,30,40,50,60,70,89]
[20, 30, 40, 50, 60, 70, 89] print(a) enter a
element to search:30 search=eval(input("enter a element to search:")) element found at
2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found") Binary search
output a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0 stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("element found at",mid+1)
break elif(search<a[mid]):
stop=mid-1 else:
start=mid+1
else:
print("not found") Two marks:
1. What is a Boolean value?
Boolean data type have two values. They are 0 and 1.

0 represents False

1 represents True

True and False are keyword.

Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0

2. Difference between break and continue.

break continue

It terminates the current loop and It terminates the current iteration and executes the
remaining statement outside transfer the control to the next iteration in the loop.
the loop.

syntax: syntax:
break continue

for i in "welcome": for i in "welcome":


if(i=="c"): if(i=="c"):
break continue print(i)
print(i)
w we
e
l lome
3. Write a Python program to accept two numbers, multiply them and print the result.

number1 = int(input("Enter first number: ")) number2


= int(input("Enter second number: ")) mul = number1
* number2
print("Multiplication of given two numbers is: ", mul)

4. Write a Python program to accept two numbers, find the greatest and print the result.
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
if(number1>number2):
print('number1 is greater',number1) else:

print('number2 is greater',number2)
5. Define recursive function.
Recursion is a way of programming or coding a problem, in which a function calls itself one or
more times in its body. Usually, it is returning the return value of this function call. If a function definition
fulfils the condition of recursion, we call this function a recursive function.

Example:

def factorial(n):
if n == 1:
return 1 else:
return n * factorial(n-1)

6. Write a program to find sum of n numbers:

n=eval(input("enter n")) enter n i=1


10 sum=0 55
while(i<=n):
sum=sum+i
i=i+1 print(sum)

7. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.

It is used when a statement is required syntactically but you don’t want any code to execute.

It is a null
statement,
nothing
happens when
it is executed.
Syntax: pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e pass
l print(i) co
m

8. Compare string and string slices.


A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg: >>> s ='Monty Python'
>>> print s[0:5] Monty
>>> print s[6:12] Python

9. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we define a variable
on the top of the script or module, the variable is called global variable. The variables that are defined inside a
class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)

10. Mention a few string functions.


s.captilize() – Capitalizes first character of string s.count(sub)
– Count number of occurrences of string s.lower() – converts
a string to lower case
s.split() – returns a list of words in string

LISTS, TUPLES, DICTIONARIES

1. Insertion sort
Insertion sort is an elementary sorting algorithm that sorts one element at a time. Most
humans, when sorting a deck of cards, will use a strategy similar to insertion sort. The algorithm
takes an element from the list and places it in the correct location in the list. This process is repeated
until there are no more unsorted items in the list.
Example:
Program:
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("Before sorting",a) for
i in range(1,n): key=a[i]
j=i-1
while j>=0 and key<a[j]:
a[j+1]=a[j] j-
=1 a[j+1]=key
print("After sorting(using insertion sort)",a)

Output
Enter size of list6
Enter listelements4
Enter listelements33
Enter list elements6
Enter listelements22
Enter list elements6
Enter list elements-9
Before sorting [4, 33, 6, 22, 6, -9]
After sorting(using insertion sort) [-9, 4, 6, 6, 22, 33] 2. Selection Sort
The selection sort algorithm starts by finding the minimum value in the array and moving it to the first
position. This step is then repeated for the second lowest value, then the third, and so on until the array is
sorted.
Example
Program a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("List before sorting",a)
for i in range(0,n):
j=i+1
for j in range(j, n):
if a[i]> a[j]:
temp=a[i]
a[i]=a[j]
a[j]=temp
print("Sorted list(using Selection Sort)=",a)

Output:
Enter size of list5
Enter list elements12
Enter list elements-5
Enter list elements4
Enter listelements48
Enter listelements98
List before sorting [12, -5, 4, 48, 98]
Sorted list(using Selection Sort)= [-5, 4, 12, 48, 98] 3. Quadratic Equation:
Formula :
ax2+bx+c = -b±√b2 – 4ac
Program 2a

import cmath
a = int(input("Enter the coefficients a:"))
b=int(input("Enter the coefficients b: "))
c = int(input("Enter the coefficients c: "))
d = b**2-4*a*c # discriminant
x1 = (-b+cmath.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-cmath.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Output
Enter the coefficients a: 5
Enter the coefficients b: 1
Enter the coefficients c: 2
This equation has two solutions: (-0.1+0.6244997998398398j) or (-0.1-0.6244997998398398j)

Enter the coefficients a: 1


Enter the coefficients b: -5
Enter the coefficients c: 6
This equation has two solutions: (3+0j) or (2+0j)

4. Merge sort
Merge sort works as follows:
a. Divide the unsorted list into n sub lists, each containing 1 element (a list of 1 element is
considered sorted).
b. Repeatedly merge sub lists to produce new sorted sub lists until there is only 1 sub list
remaining. This will be the sorted list.
Example

Program:

def merge(left, right):


result = []
i, j = 0, 0
while (i < len(left) and j<len(right)):
if left[i] < right[j]:
result.append(left[i]) i+= 1
else:
result.append(right[j])
j+= 1 result=result+left[i:]
result=result+right[j:] return result
def mergesort(list): if len(list) <
2: return list
middle = len(list)//2
left = mergesort(list[:middle]) right =
mergesort(list[middle:]) return merge(left,
right)
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("Unsorted list is",a)
print("Sorted list using merge sort is",a)

Output
Enter size of list5
Enter list elements21
Enter list elements1
Enter list elements-8
Enter list elements14
Enter list elements18
Unsorted list is [21, 1, -8, 14, 18]
Sorted list using
merge sort is [-8, 1,
14, 18, 21] 5.
LIST
o List is a sequence of values, which can be of different types. The values in list are called
"elements" or ''items''
o Each elements in list is assigned a number called "position" or "index"
o A list that contains no elements is called an empty list. They are created with empty
brackets[]
o A list within another list is nested list

Creating a list :
The simplest way to create a new list is to enclose the elements in square brackets ([])
[10,20,30,40]
[100, "python" , 8.02]

1.LIST OPERATIONS:
1.Concatenation of list
2.Repetition of list

Concatenation: the '+' operator concatenate list


>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a+b
>>> Print (a*2) => [1,2,3,1,2,3]

Repetition: the '*' operator repeats a list a given number of times


>>> a = [1,2,3]
>>> b = [4,5,6]
>>> print (a*2)= [1,2,3,1,2,3]

2. List looping: (traversing a list)


1. Looping in a list is used to access every element in list
2."for loop" is used to traverse the elements in list eg:
mylist = ["python","problem",100,6.28]
for i in range (len (mylist)):
print (mylist [i])
3.List Slices:
A subset of elements of list is called a slice of list. Eq: n =
[1,2,3,4,5,6,7,8,9,10]
print (n[2:5]) print (n[-5]) print (n[5: ]) print (n[ : ]) 4.Aliasing and cloning:
when more than one variables refers to the same objects or list, then it is called aliasing.

a= [5,10,50,100]
b=a
b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) = [80,5,10,50,100]
Here both a & b refers to the same list. Thus, any change made with one object will affect other, since
they are mutable objects.
in general, it is safer to avoid aliasing when we are working with mutable objects

5. Cloning:
Cloning creates a new list with same values under another name. Taking any slice of list create new
list.
Any change made with one object will not affect others. the easiest way to clone a new list is to use
"slice operators"
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100] Print ("
cloning list", b) = [5,10,50,100]

List parameter:
List can be passed as arguments to functions the list arguments are always passed by reference only.
Hence, if the functions modifies the list the caller also changes. Eq:
def head ():
del t[ 0 ]
>>> letters = ['a','b','c']
>>> head (letters)
>>> letters
['b','c']
In above,
The parameters 't' and the variable 'letters' or aliases for the same objects An
alternative way to write a function that creates and return a new list Eq:
def tail (t):
return t [1:]
>>> letters = ['a','b','c']
>>> result = tail (letters)
>>> result
['b','c']
In above,
The function leaves the original list unmodified and return all element in list except first element 6.
TUPLES:
A tuple is a sequence of value which can be of any type and they are indexed by integers. Values in
tuple are enclosed in parentheses and separated by comma. The elements in the tuple cannot be modified as in
list (i.e) tuple are immutable objects

Creating tuple:
Tuple can be created by enclosing the element in parentheses separated by comma t =
('a','b','c','d')
To create a tuple with a single element we have to include a final comma
>>> t = 'a',
>>> type (t)
< class 'tuple'>
Alternative way to create a tuple is the built-in function tuple which mean, it creates an empty tuple
>>> t = tuple ()
>>> t
>>> ( )
Accessing element in tuple:
If the argument in sequence, the result is a tuple with the elements of sequence.
>>>t= tuple('python')
>>> t
('p','y','t','h','o','n')
t = ('a','b',100,8.02)
print (t[0]) = 'a'
print (t[1:3]) = ('b', 100 , 8.02)

Deleting and updating tuple:


Tuple are immutable, hence the elements in tuple cannot be updated / modified
But we can delete the entire tuple by using keyword 'del' Eg 1: a =
(' programming', 200, 16.54, 'c', 'd')
#Try changing an element.
a[ 0 ] = 'python' <-------- Error,modifying not possible print (a
[0])
Eg: # Deletion of tuple a =
('a','b','c','d')
del (a) :-------- delete entire tuple
del a [1] <--------- error,deleting one element in tuple not possible
Eg: # replacing one tuple with another a =
('a','b','c','d')
t = ('A',) + a[1: ]
print (t) <------ ('a','b','c','d') Tuple Assignment:
Tuple assignment is often useful to swap any number of values
the number of variables in left and right of assignment operators must be equal
A single assignment to paralleling assign value to all elements of tuple is the major benefit of tuple
assignment
Eg: Tuple swapping in python
A= 100
B= 345
C= 450
print (" A & B:", A,"&",B)
# Tuple assignments for two
variables A,B = B,A
print (" A&B after tuple assignment : ",A,"&",B)
# Tuple assignment can be done for no of
variables A,B,C = C,A,B
print (" Tuple assignment for more variables:",
A,"&",B,"&",C) Output
A & B: 100 & 345
A&B after tuple assignment : 345 & 100
Tuple assignment for more variables: 450 & 345 & 100

Tuple as return value:


Generally, function can only return one value but if the value is tuple the same as returning the
multiple value
Function can return tuple as return value
Eg: # the value of quotient & remainder are returned as tuple def
mod_div
(x,y): quotient
= x/y remainder
= x%y
return quotient, remainder
# Input the seconds & get the hours minutes &
second sec = 4234 minutes,seconds=
mod_div (sec,60)
hours,minutes=mod_div(minutes,
60)
print("%d seconds=%d hrs:: %d min:: %d sec"%
(sec,hours,minutes,seconds)) Output:
4234onds=1 hrs:: 10 min:: 34 sec
dictionary
A dictionary is an unordered set of key: value pair. In a list, the indices have to be integers; in a
dictionary they can be any type. A dictionary contains a collection of indices, which are called keys, and a
collection of values. Each key is associated with a single value. The association of a key and a value is called
a key-value pair. Dictionary is created by enclosing with curly braces {}.
Eg:
>>>
dictionary={"RollNo":101,2:(1,2,3),"Name":"Ramesh",20:20.50,Loc":['Chennai']}
>>> dictionary
{'Name':'Ramesh', 'Loc':['Chennai'], 2:(1,2.3), 20: 20.0, 'RollNo': 101}

What is data structure


A data structure is a particular way of organizing and storing data in a computer so that it can be accessed
and modified efficiently.
Python data structures:-
1. List
2. Tuples
3. Dictionary

5. Compare all the three data structures in Python

List Tuples Dictionary


Mutable List is mutable Tuples are immutable Keys must be immutable. Values
may mutable Indexing A positive integer is used for indexing and always starts with zero. Reverse
index is supported.
A positive integer is used for indexing and always starts with zero. Reverse index is supported.
Indexing is done with ‘key’. Index may be of any type. Values can be accessed only through key
Declaration List=[05,’Ashok’,450] Tuple=(‘Sun’,’Mon’) Dictionary={“Key”:”value”}

Difference between list append and list extend


1. append() is a function adds a new element to the end of a list.
2. extend() is a function takes a list as an argument and appends all of the elements.

append() extend() >>>a=[10,20,30]


>>>b=[40,50]
>>>a.append(b)
>>>print(a) [10,20,30,[40,50]]
>>>a=[10,20,30]
>>>b=[40,50]
>>>a.extend(b)

>>>print(a) [10,20,30,40,50]
 It is used to append (add) a string into a file
 If file is not exist it creates a new file
 It will add the string at the end of the old file

MODULES IN PYTHON
 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.
1.Import statement:
 An import statement is used to import python module in some python source file.
Syntax: import module1 [, module2 […module]]
Example:
>>>import math
>>>print (math.pi)
3.14159265

2.Import with renaming:


The import a module by renaming it as follows,
>>>import math as a
>>>print(“The value of pi is “,a.pi)
The value of pi is 3.14159265
Writing modules:
 Any python source code file can be imported as a module into another python source file. For
example, consider the following code named as support.py, which is python source file defining two
function add(), display().
Support.py:
def add(a,b):
print(“The result is “,a+b)
return
def display(p): print(“welcome “,p) return
The support.py file can be imported as a module into another python source file and its functions can
be called from the new files as shown in the following code:
3. Import file name

import support #import module support

support.add(3,4) #calling add() of support module with two integers support.add (3.5,4.7) #calling add() of
support module with two real values support.add (‘a’,’b’) #calling add() of support module with two character
values support.add (“yona”,”alex”)#calling add() of support module with two string values support.display
(‘fleming’) #calling display() of support module with a string value Output:
The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome, fleming
4. from……import statement:

 It allows us to import specific attributes from a module into the current namespace.
Syntax: from modulename import name1 [, name2[,……nameN]]
from support import add #import module support
support.add(3,4) #calling add() of support module with two integers support.add(3.5,4.7)
#calling add() of support module with two real values support.add(‘a’,’b’) #calling add() of
support module with two character values support.add (“yona”,”alex”)#calling add() of support
module with two string values support.display (‘fleming’) #calling display() of support module
with a string value

Output:
The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome, fleming

5.OS Module

 The OS module in python provide function for interacting with operating system
 To access the OS module have to import the OS module in our program
import os
method example description
name Osname ‘nt’ This function gives the name of the operating
system getcwd() Os,getcwd()
,C;\\Python34’
Return the current working directory(CWD)of the file used to execute the code mkdir(folder)
Os.mkdir(“python”) Create a directory(folder)
with the given name
rename(oldname,newname) Os.rename(“python”,”pspp”) Rename the directory or folder
remove(“folder”) Os.remove(“pspp”) Remove (delete)the directory or folder getuid()
Os.getuid() Return the current process’s
user id
environ Os.nviron Get the users environment

6.Sys Module

 Sys module provides information about constant, function and methods


 It provides access to some variables used or maintained by the interpreter
import sys

methods example description sys.argv


sys.argv

sys.argv(0)

sys.argv(1)
Provides the list of command line arguments passed to a python script Provides to access the file name
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
‘win32’

sys.exit sys.exit
<built.in function exit>
Provide information about the operating system platform
Exit from python

Steps to Create the Own Module


 Here we are going to create a calc module ; our module contains four functions i.e
add(),sub(),mul(),div()

Program for calculator module output Module name ;calc.py def add(a,b); print(a+b)
def sub(a,b);
print(a-b) def mul(a,b); print(a*b)
def div(a,b);
print(a/b)
import calculator calculator.add(2,3)

Outcome
>>>5

Introduction to Python: Python is an easy to learn, powerful programming language. It


combines the features of C and JAVA. It has efficient high-level data structures and a simple but effective
approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together
with its interpreted nature, make it an ideal language for scripting and rapid application development in
many areas on most platforms.
Python is open source software, which means anybody can freely download it from
www.python.org and use it to develop programs. Its source code can be accessed and modified as
required in the projects.
Features of python:
1. Simple: Python is a simple and minimalistic language. Reading a good Python program feels almost like
reading English language. It means more clarity and less stress on understanding the syntax of the
language. It allows you to concentrate on the solution to the problem rather than the language itself.
2. Easy to learn: Python uses very few keywords. Python has an extraordinarily simple syntax and simple
program structure.

3. Open Source: There is no need to pay for Python software. Python is FLOSS (Free/Library and Open
Source Software). It can be free downloaded from www.python.org website. Its source can be read,
modified and used in programs as desired by the programmers.
4. High level language: When you write programs in Python, you never need to bother about the low-
level details such as managing the memory used by your program, etc.
5. Dynamically typed: Python provides IntelliSense. IntelliSense to make writing your code easier and
more error-free. IntelliSense option includes statement completion, which provides quick access to valid
member function or variables, including global, via the member list. Selecting from the list inserts
the member into your code.
6. Portable: Due to its open-source nature, Python has been ported to (i.e. changed to make it work on)
many platforms. All your Python programs can work on any of these platforms without requiring any
changes at all if you are careful enough to avoid any system-dependent features.

7. Platform independent: When a Python program is compiled using a Python compiler, it


generates byte code. Python’s byte code represents a fixed set of instructions that run on all operating
systems and hardware. Using a Python Virtual Machine (PVM), anybody can run these byte code
instructions on any computer system. Hence, Python programs are not dependent on any specific
operating system.

8. Procedure and Object Oriented: Python supports procedure-oriented programming as well as


object-oriented programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In object- oriented languages,
the program is built around objects which combine data and functionality.
Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages
like C++ or Java.
9. Interpreted: Python converts the source code into an intermediate form called byte codes and then
translates this into the native language of your computer using PVM(Is s interpreter) and then runs it.

10. Extensible: The programs or function written in C / C++ can be integrated into Python an executed
using PVM. There is another flavor of Python where programs from other languages can be integrated into
Python.

11. Embeddable: You can embed Python within your C/C++ programs to give scripting
capabilities for your program’s users.

12. Extensive Libraries: The Python Standard Library is huge indeed. It can help you do various things
involving regular expressions, documentation generation, unit testing, threading, databases, web browsers,
CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and
other system-dependent stuff. Remember, all this is always available wherever Python is installed.
This is called the Batteries Included philosophy of Python.
Some interesting batteries or packages are:
 orgparse is a package that represents command-line parsing library
 botois Amazon web services library
 cherryPhy is an object-oriented HTTP frame work
 cryptography offers cryptographic techniques for the programmers.
 fiona reads and writes big data files.
 numpy is package for processing arrays of single or multidimensional type.
 w3lib is a library of web related functions.
 mysql-connector-pythonis is a driver written in Python to connect to MySQL data base.

13. Scripting language: Python is considered as scripting language as it is interpreted and it is used on
the Internet to support other software.

14. Database connectivity: Python provides interface to connect its programs to all major databases
like Oracle, Sybase or MySQL.

15. Scalable: Python programs are scalable since they can run on any platform and use the features of
the new platform effectively.

Comparison between C and Python


C-Language Python
Procedure Oriented Programming Language Object Oriented Programming Language Program
execute faster Program execute slower compare to C Declaration of
variable is compulsory Type declaration is NOT required.
Type discipline is static and weak Type discipline is dynamic and string
Pointer is available No pointer
Does not have exception handling Handles exceptions
It has while, for and do-while loops It has while and for loops
It has switch-case statement It does not have switch-case statement The variable in for
loop does not incremented automatically.
Memory allocation and de-allocation is not automatic
The variable in the for loop incremented automatically.
Memory allocation and de-allocation is done automatically by PVM. It does not contain a garbage
collection Automatic garbage collection
It supports single and multi dimensional arrays It supports only single dimensional array.
Implement multi dimensional array we should use third
party application like numpy.
The array index should be positive integer. Array index can be positive and negative integer.
Negative index represents location from the end of the
array.
Indentation of statements in not necessary Indentation is required to represents a block of
statements. A semicolon is used to terminate the statements and comma is used to separate
expressions / variables.
New line indicates end of the statements and semicolon is used as an expression separator. It supports in-
line assignment It does not supports in-line assignment.

Comparison between Java and Python


Java Python
Pure Object-Oriented Programming Language Both Object-Oriented and Procedure-Oriented
programming language
Java programs are verbose. Python programs are concise and compact.
Declaration of variable is compulsory Type declaration is NOT required.
Type discipline is static and weak Type discipline is dynamic and string
It has while, for and do-while loops It has while and for loops
It has switch-case statement It does not have switch-case statement The variable in for
loop does not incremented automatically.
Memory allocation and de-allocation is automatically by JVM
The variable in the for loop incremented automatically.
Memory allocation and de-allocation is done automatically by PVM. It supports single and multi
dimensional arrays It supports only single dimensional array.
Implement multi dimensional array we should use third
party application like numpy.
The array index should be positive integer. Array index can be positive and negative integer.
Negative index represents location from the end of the
array.
Indentation of statements in not necessary Indentation is required to represents a block of
statements. A semicolon is used to terminate the statements and comma is used to separate
expressions / variables.
The collection objects like stack, linked list or vector but not primitive data types like int, float, char
etc.,
New line indicates end of the statements and semicolon is used as an expression separator.

The collection objects like lists and dictionaries can store objects of any type including numbers and
lists.
Python Virtual Machine (PVM) or Interpreter
Python converts the source code into byte code. Byte code represents the fixed set of
instructions created by Python developers representing all types of operations. The size of each
byte code instruction is 1 byte.

The role of PVM is to convert the byte code instructions into machine code. So that the
computer can execute those machine code instruction and display the final output. The PVM is also called
as interpreter.

Python Shell
Python Interpreter is a program which translates your code into machine language and then executes
it line by line.
We can use Python Interpreter in two modes:
1. Interactive Mode.
2. Script Mode.
In Interactive Mode, Python interpreter waits for you to enter command. When you type the command,
Python interpreter goes ahead and executes the command, then it waits again
for your next command.
In Script mode, Python Interpreter runs a program from the source file.

Interactive Mode
Python interpreter in interactive mode is commonly known as Python Shell. To start the
Python Shell enter the following command in terminal or command prompt:

To start the Python 3 Shell enter python3 instead of just python.


1 q@vm:~$ python3
2 Python 3.5.2 (default, Nov 17 2016, 17:05:23)
3 [GCC 5.4.0 20160609] on linux
4 Type "help", "copyright", "credits" or "license" for more information.
5 >>>
What you are seeing is called Python Shell. >>>is known as prompt string, it simply means that Python
shell is ready to accept you commands. Python shell allows you type Python code and see the result
immediately.
In Python shell, enter the following calculations one by one and hit enter to get the result.

>>>
>>> 88 + 4
92
>>> 45 * 4
180

Script Mode
Python Shell is great for testing small chunks of code but there is one problem – the
statements you enter in the Python shell are not saved anywhere.
In case, you want to execute same set of statements multiple times you would be better off to save the
entire code in a file. Then, use the Python interpreter in script mode to execute the code from a file.
Create a new file named example.pyand following code to it:
print("Welcome to Python Program")
print("BCA 6th Sem")
print("SSCASC Tumkur")
By convention, all Python programs have .pyextension. The file example.pyis called source
code or source file or script file or module. Execute by typing the following command an obtained out
as follows,
$ python example.py Welcome to
Python Program BCA 6th Sem
SSCASC Tumkur

Indentation: Whitespace is important in Python. Actually, whitespace at the beginning of the line is
important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical
line is used to determine the indentation level of the logical line, which in turn is used to determine the
grouping of statements.

This means that statements which go together must have the same indentation. Each such set of
statements is called a block. One thing you should remember is that wrong indentation can give rise to
errors

Basic elements of Python


1. Comments : Comments are non-executable statements. It means neither compiler nor
PVM will not execute them. Comments are any text to the right of the # symbol and is mainly
useful as notes for the reader of the program. There are two types of comments in Python, Single
line comments and Multiline comments
a. Single line Comments: this comment starts with a hash symbol (#) and are useful to mention
that the entire line till the end should be treated as comments.
Eg. # To find the sum of two number
k=5 # assign 5 to variable k.
In the above example, first line starts with # and hence the total line treated as
comments. In second line part of this line starting from # to the end of the line treated as
comments.
b. Multi line Comments: The triple double quotes (“””) or triple single quotes (‘’’) are
called multi line comments or block comments. They are used to enclose a block of lines as
comments.
Eg-1. “”” This is illustrated as multi line comments
To find the sum of two number
Using Triple double quotes
“””
2. Identifiers: Identifier is the name given to various program elements like variables,
function, arrays, classes, strings etc.,

The Python identifiers follow the following rules:

i. The Name should begin with an alphabet.


ii. Only alphabets, digits and underscores are permitted.
iii. Distinguish between uppercase and lowercase alphabets. iv.
Keywords should not be used as identifiers.
v. No blank space between the identifiers.
e.g. Valid Identifiers : Area
area_tri num1
3. Keywords: The keywords have predefined meaning assigned by the Python Complier.
The keywords are also called as reserved word. All keywords are written in lower case alphabets.
The Python keywords are:

and del for lambda true

as elif from not try


assert else global or while
break except if pass with class

exec import print yield continue false

in raise

def finally is return

4. Variable: Is a program element, whose value changes during the execution of the
program. Unlike other programming languages, Python has no command for declaring a
variable.
A variable is created the moment you first assign a value to it.
Eg. x=5;
y=”kvn”
Variables do not need to be declared with any particular type and can even change type after
they have been set.
5. Constants: Constant is a program element, while execution of a program the value does
not change. A constant gets stored in a memory location but the address of the location is not
accessible to the programmer

Assigning value to a constant in Python

In Python, constants are usually declared and assigned on a module. Here, the module means a new file
containing variables, functions etc which is imported to main file.
Inside the module, constants are written in all capital letters and underscores separating the words.

Eg.:

Create a constant.py
PI = 3.14

6. Literals : Literal is a raw data given in a variable or constant. In Python, there are
various types of literals they are as follows:

a. Numeric Literals : Numeric Literals are immutable (unchangeable). Numeric literals can
belong to 3 different numerical types Integer, Float and Complex.
E.g. a=5 # integer literal b=2.5
# float literal c=3.5j # complex
literal

b. String literals : A string literal is a sequence of characters surrounded by quotes. We can use both
- single, double or triple quotes for a string. Character literal is a single character surrounded by
single or double quotes.
E.g. str=”SSCASCT”

c. Boolean literals : A Boolean literal can have any of the two values: True or False.
E.g. x=true
Y=false

d. Special literals: Python contains one special literal i.e. None. We use it to specify to that field
that is not created.

E.g. k=none
7. Data Types: A data type represents the type of data stored into a variable or memory.
There are 5 different data types are:
 None type
 Numeric type
 Sequences
 Sets
 Dictionary
i. None data type : The none data type represents an object that does not contain
any value. In java language it is called “NULL” object. But in Python it is
called as “none”. In Python maximum of only one ‘none’ object is provided.
If no value is passed to the function, then the default value will be taken as
‘none’.
ii. Numeric data type: The numeric type represents numbers. There are 3 sub types:
 int
 float
 complex
int data type: The int data type represents integer number (Whole number). An
integer number is number without fraction. Integers can be of any length, it is only
limited by the memory available.
E.g. a=10 b=-29
float data type: The float data type represents floating point number. A
floating point number is a number with fraction. Floating point numbers can also be
written in scientific notation using exponentiation format.
A floating point number is accurate up to 15 decimal places. Integer and floating points
are separated by decimal points.
complex data type: A complex number is number is written in the form of x
+yj or x+yJ. Here x is the real part and y is the imaginary part.
We can use the type() function to know which class a variable or a value belongs to and
the isinstance() function to check if an object belongs to a particular class. E.g.
a=5
print(a, "is of type", type(a))
b = 2.0
print(a, "is of type", type(b))
iii. Sequences: A sequence represents a group of items or elements. There are six
types of sequences in Python. Important sequences as follows,
 str
 list
 tuple
str data type : The str represents string data type. A string is a collection of character
enclosed in single or double quotes. Both are valid.
E.g. str=”kvn” # str is name of string variable
str=’vedish’ # str is name of string variable
Triple double quote or triple single quotes are used to embed a string in a another
string (Nested string).
str=”””This is ‘str data type’ example”””
print(str) # output is : This is ‘str data type’ example
The [] operator used to retrieve specified character from the string. The string
index starts from 0. Hence, str[0] indicates the 0 th character in the string.
e.g str=” SSCASC Tumkur”
print(str) # it display - SSCASC Tumkur
print(str[0]) # it display - G

list data type: A List is a collection which is ordered and changeable. It allows
duplicate members. A list is similar to array. Lists are represented by square brackets
[] and the elements are separated by comma.

The main difference between a list and an array is that a list can store
different data type elements, but an array can store only one type of
elements. List can grow dynamically in memory but the size of array is fixed and they
cannot grow dynamically.

e.g. list=[10,3.5,-20, “SSCASCT”,’TUMKUR’] # create a list


print(list) # it display all elements in the list : 10,3.5,-20,
“SSCASCT”,’TUMKUR’

tuple data type: A tuple is similar to list. A tuple contains group of elements
which can be different types. The elements in the tuple are separated by
commas and enclosed in parentheses (). The only difference is that tuples
are immutable. Tuples once created cannot be modified. The tuple cannot change
dynamically. That means a tuple can be treated as read-only list.

e.g. tpl=(10,3.5,-20, “SSCASCT”,’TUMKUR’) # create a tuple


print(tpl) # it display all elements in the tuple : 10,3.5,-20,
“SSCASCT”,’TUMKUR’

iv. Sets: Set is an unordered collection of unique items and un-indexed. The order
of elements is not maintained in the sets. A set does not accept duplicate
elements. Set is defined by values separated by comma inside braces { }.
There are two sub types in sets:
 Set data type
 Frozen set data type
Set data type: To create a set, we should enter the elements separated by comma
inside a curly brace.
e.g. s = {10,30, 5, 30,50}
print(s) # it display : {10,5,30,50}
In the above example, it displays un-orderly and repeated elements only once,
because set is unordered collection and unique items.
We can use set() to create a set as
K=set(“kvn”)
Print(K) # it display : “kvn”

Frozen set data type: Frozen set is just an immutable version of a Python set object.
While elements of a set can be modified at any time, an element of frozen set remains
the same after creation. Due to this, frozen sets can be used as key in Dictionary or as
element of another set.

v. Dictionary: A dictionary is an unordered collection, changeable and indexed. In


Python dictionaries are written with curly brackets, and they have keys and values. That
means dictionary contains pair of elements such that first element represents the key and the
next one becomes its value. The key and value should be separated by a colon(:) and every
pair should be separated by comma. All the elements should be enclosed inside curly
brackets. e.g.
d={3: ‘sscasc’, 4:’tumkur’, 5:’kvn’, 6: ‘vedish’} Here, d is the name of dictionary. 3 is the key and its
associated value is ‘sscasc’. The next is 4 and its value is ‘tumkur’ and so on.
Print(d) # it display : ={3: ‘sscasc’, 4:’tumkur’, 5:’kvn’, 6: ‘vedish’}
Print(d[5]) # it display : kvn

String operations:
1. Extract specified character from the string. Get the character at position 1
(remember that the first character has the position 0):

a= "Hello,Python!"
print(a[6]) # it display : P
2. Substring: Extract number of character from the specified position. Get the characters
from position 2 to position 5 (not included):
b= "Hello,Python!"
print(b[6:8]) # it display : Ph
3. The strip() method removes any whitespace from the beginning or the end of the given
string.
a= " Hello,Python! "
print(a.strip()) # it display : "Hello,Python!"

4. The len() method returns the length of a given string


a= " Python"
print(a.len()) # it display : 6

5. The lower() method returns the given string in lower case.


a= " PYTHON"
print(a.lower()) # it display : python

6. The upper() method returns the given string in upper case.


a= " python"
print(a.upper()) # it display : PYTHON

7. The replace() method replaces a given string with another string


a= "FOR"
print(a.replace(‘O’ , ‘A’)) # it display : FAR

8. The split() method splits the string into substrings if it finds instances of the
separator
a= "Hello,Python!"
print(a.split(‘,’)) # it display : [ ‘Hello’ , ‘Python’}

Operator and Operand:


Operators are special symbols which represents computation. They are applied on
operand(s), which can be values or variables. Same operator can behave differently on
different data types. Operators when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and Assignment. Value and
variables when used with operator are known as operands.

1. Arithmetic Operators :
Symbol Description Example-1 Example-2 +
Addition >>> 5 + 6
11
- Subtraction >>>10-5
5
* Multiplication >>> 5*6
30
/ Division >>> 10 / 5
2
% Remainder / Modulo >>> 5 % 2
1
** Exponentiation >>> 2**3
8
// Integer Division >>> 7.0 // 2
3.0
>>>’SSCASCT’+’BCA’
SSCASCTBCA
>>>5 – 6
-1
>>>’SSCASCT’ * 2
SSCASCTSSCASCT
>>>5 /2.0
2.5
>>>15%5
0
>>>2**8
256
>>>3//2
1 2. Relational Operators :
Symbol Description Example-1 Example-2 < Less than
>>> 7<10
True
>>> ‘SSCASCT’ <’BCA’
False > Greater Than >>> 7 >10
False
<= Less than or equal to >>> 7<=10
True
>= Greater than or equal to >>> 7>=10
False
!= , <> Not equal to >>> 7!=10
True

== Equal to >>> 7==10


False

3. Logical Operators :
>>>’SSCASCT’ > ‘BCA’
True
>>>’SSCASCT’ <=’BCA’
False
>>>’SSCASCT’>=’BCA’
True
>>>’SSCASCT’!=
‘sscasct’
True
>>>’SSCASC’
==’SSCASC’
True Symbol Description Example-2 or If any one of the
operand is true, then condition becomes TRUE
and If both the operands are true, then the condition becomes TRUE
>>> 7<=10 or 7 ==10
True
>>>7<10 and 7 >20
False not Reverse the state of operand / condition >>> not 7<10
False

4. Assignment Operator:
Symbol Description Example-1 = Assigned values from right
side operands to left variable.
>>> x=10
10
Variations of Assignment Operators:
Compound Assignment Operator combines the effect of arithmetic and assignment operator, the
original value of x =5

Symbol Description Example-1 += added and assign back the


result to left operand
-= subtracted and assign back the result to left operand
*= multiplied and assign back the
result to left operand
/= divided and assign back the result to left operand
%= taken modulus using two operands and assign the result to left operand
**= performed exponential (power) calculation on operators and assign value to the left
operand
//= performed floor division on operators and assign value to
>>> x+=2
7
>>> x-=2
3
>>> x*=2
10
>>> x/=2
2
>>> x%=2
1

>>> x**=2
25

>>> x//=2
2.5
the left operand

5. Bitwise Operator: a bit is the smallest unit of data storage and it can have only one
of the two values, 0 and 1. Bitwise operators works on bits and perform bit-by-bit
operation.

Symbol Description Example


| Performs binary OR operation 5 | 3 gives 7
& Performs binary AND operation 5 & 3 gives 1
~ Performs binary XOR operation 5 ^ 3 gives 6
^ Performs binary one's complement operation ~5 gives -6 << Left shift operator:
The left-hand side operand bit is moved left by the number specified on the right-hand side
(Multiply by 2)
>> Left shift operator: The left-hand side operand bit is moved left by the number
specified on the right-hand side (Divided by 2)
0010 << 2 gives 8

0100 << 2 gives 1


6. Membership operators: Python has membership operators, which test for
membership in a sequence, such as strings, lists or tuples. There are two
membership operators are:
Symbol Description Example in Returns True if the
specified operand is found in the sequence

Not in Returns True if the specified operand is found in the sequence


>>> x = [1,2,4,6,8]
>>> 3 in x
false
>>> x = [1,2,4,6,8]
>>> 3 not in x
true
7. Identity operator: Identity operators compare the memory locations of two
objects. There are two Identity operators are:
Symbol Description Example Example is Returns True if two
variables point to the same object and False, otherwise

is not Returns False if two variables point to the same object and True, otherwise
>>>X=10
>>>Y=10
>>> X is Y
true
>>>X=10
>>>Y=10
>>> X is not Y
false
>>> x=[1,2,3]
>>> y=[1,2,3]
>>> x is y false
>>> x=[1,2,3]
>>> y=[1,2,3]
>>> x is not y true

Input function
CHAPTER 2
CREATING PYTHON PROGRAM The print function enables a Python program to display textual
information to the user. Programs may use the input function to obtain information from the user. The
simplest use of the input function assigns a string to a variable:
x = input()
The parentheses are empty because the input function does not require any
information to do its job. usinginput.py demonstrates that the input function produces a string
value.

Exaple: Demonstrates that the input function


print('Please enter some text:')
x = input()
print('Text entered:', x)
print('Type:', type(x))
Since user input always requires a message to the user about the expected input, the input
function optionally accepts a string and prints just before the program stops to wait for the user to
respond.

The statement variable = input("Enter a value: ")


The value entered is a string. You can use the function eval to evaluate and convert it to a
numeric value.
Example: eval("34.5") returns 34.5, eval("345") returns 345.
Example: Compute area with console input
# Prompt the user to enter a radius
radius = eval(input("Enter a value for radius: "))
# Compute area
area = radius * radius * 3.14159
#Display results
print("The area for the circle of radius",radius,"is",area)
Compute Average
# Prompt the user to enter three numbers
number1 = eval(input("Enter the first number: ")) number2
= eval(input("Enter the second number: ")) number3 =
eval(input("Enter the third number: "))
# Compute average
average = (number1 + number2 + number3) / 3
# Display result
print("The average of", number1, number2, number3,"is",average)
Print Function
The print a line of text, and then the cursor moves down to the next line so any future printing appears
on the next line.
print('Please enter an integer value:')
The print statement accepts an additional argument that allows the cursor to remain on the same line as
the printed text:
print('Please enter an integer value:', end=' ')
The expression end=' ' is known as a keyword will cause the cursor to remain on the same line as the
printed text. Without this keyword argument, the cursor moves down to the next line after printing the
text.
Another way to achieve the same result is
print(end='Please enter an integer value: ')
This statement means “Print nothing, and then terminate the line with the string
'Please enter an integer value:' rather than the normal \n newline code. The statement
print('Please enter an integer value:', end='\n')
that is, the default ending for a line of printed text is the string '\n', the newline control code.
Similarly, the statement
print( )
is a shorter way to express
print(end='\n')
By default, the print function places a single space in between the items it
prints. Print uses a keyword argument named sep to specify the string to use insert between items. The
name sep stands for separator. The default value of sep is the string ' ', a string containing a single
space. The program printsep.py shows the sep keyword customizes print’s behaviour.
Program to illustrate sep:
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=' , ') print(w,
x, y, z, sep=' ') print(w, x, y, z,
sep=' : ') print(w, x, y, z,
sep='-----')

The output
10 15 20 25
10,15,20,25
10 15 20 25
10:15:20:25
10-----15-----20-----25

Formatting Numbers and Strings


Format function is used to return a formatted string for displaying numbers in a certain
desirable format. For example, the following code computes interest, given the amount and the annual
interest rate.
>>> amount = 12618.98
>>> interestRate = 0.0013
>>> interest = amount * interestRate
>>> print("Interest is", format(interest, ".2f "))
Interest is 16.40
>>>
The syntax to invoke this function is
format(item, format-specifier)
Where item is a number or a string and format-specifier is a string that specifies how the
item is formatted. The function returns a string.

Frequently Used Specifiers


Specifier Format

"10.2f" Format the float item with width 10 and precision 2.

"10.2e" Format the float item in scientific notation with width 10 and precision
2.

"5d" Format the integer item in decimal with width 5.

"5x" Format the integer item in hexadecimal with width 5.

"5o" Format the integer item in octal with width 5.

"5b" Format the integer item in binary with width 5.

"10.2%" Format the number in decimal.

"50s" Format the string item with width 50.

"<10.2f” Left-justify the formatted item.

">10.2f" Right-justify the formatted item.

Placeholder substitution within a formatting string

print('{0} {1}'.format(2, 10**2))


This expression has two main parts:
• '{0} {1}': This is known as the formatting string. It is a Python string because it is a
sequence of characters enclosed with quotes. Notice that the program at no time prints the
literal string {0} {1}. This formatting string serves as a pattern that the second part of the
expression will use. {0} and {1} are placeholders, known as positional parameters, to be
replaced by other objects. This formatting string, therefore, represents two objects separated by a
single space.
• format(2, 10**2): This part provides arguments to be substituted into the formatting string. The first
argument, 2, will take the position of the {0} positional parameter in the formatting string. The value of
the second argument, 10**2, which is 100, will replace the {1} positional parameter.

Program to Illustrate Format Specifier print(format(57.467657,


"10.2f")) print(format(57.467657, "10.2e"))
print(format(0.53457, "10.2%"))
print(format(59832, "10d")) print(format(59832,
"<10d"))#Left Justfy
print(format(59832, "10x"))#Converts to HexaDecimal
print(format("Welcome to Python", "20s")) print(format("Welcome
to Python", "<20s")) print(format("Welcome to Python",
">20s"))#Right Justify print('{0} {1}'.format(7,10**7))
print('Sum of {0} and {1} is {2}'.format(4,5,4+5))

Output

CONTROL STATEMENTS

If Statements
A one-way if statement executes the statements if the condition is true. The syntax for a one-way if
statement is:
if boolean-expression:
statement(s) # Note that the statement(s) must be indented

• The reserved word if begins a if statement.


• The condition is a Boolean expression that determines whether or not the body will
be
executed. A colon (:) must follow the condition.
• The block is a block of one or more statements to be executed if the condition is true.
The statements within the block must all be indented the same number of spaces from
the left. The block within an
Example:To demonstrate simple if
#Get two integers from the user
dividend = int(input('Please enter the number to divide: '))
divisor = int(input('Please enter dividend: '))
# If possible, divide them and report the result if
divisor != 0:
quotient = dividend/divisor
print(dividend, '/', divisor, "=", quotient)
print('Program finished')

Output
Please enter the number to divide: 4
Please enter dividend: 5
4 / 5 = 0.8
Program finished
>>>
If-else statements
A two-way if-else statement decides which statements to execute based on whether
the condition is true or false.
The syntax for a two-way if-else statement:
if boolean-expression:
statement(s) #for-the-true-case ,the statement(s) must be indented
else:
statement(s) #for-the-false-case

Example: To demonstrate if else


percent=float(input("Enter Percentage"))
if percent >= 90.0:
print ("congratulations, you got an A")
print ("you are doing well in this class")
else:
print ("you did not get an A")
print ("see you in class next week")

Nested if statements.
A series of tests can written using nested if statements.
Example: Nestedif percent=float(input("Enter
Percentage")) if (percent >= 90.00):
print ('congratuations, you got an A')
else:
if (percent >= 80.0):
print ('you got a B')
else:
if (percent >= 70.0):
print ('you got a C')
else:
print ('your grade is less than a C')
If_elif_else Statement
In Python we can define a series of conditionals (multiple alternatives) using if
for the first one, elif for the rest, up until the final (optional) else for anything not caught by the other
conditionals.

Example:If_elif_else score=int(input("Enter
Score")) if score >= 90.0:
grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D' else:
grade = 'F'
print("Grade=",grade)

Using else if instead of elif will trigger a syntax error and is not allowed.

Loops
It is one of the most basic functions in programming; loops are an important in every programming
language. Loops enable is to execute a statement repeatedly which are referred to as iterations. (A loop is
used to tell a program to execute statements repeatedly).
The simplest type of loop is a while loop.

The syntax for the while loop is:


while loop-continuation-condition:
# Loop body
Statement(s)# Note that the statement(s) must be indented
i = initialValue # Initialize loop-control variable
while i < endValue:
# Loop body
...
i += 1 # Adjust loop-control variable

Example1: To demonstrate while


count = 0#Program to print “Programming is fun!” for 10 times
while count < 10:
print("Programming is fun!")
count = count + 1

Example2:
#program to read a series of values from the user, count the
#number of items, and print their count, sum and average.
#User indicates the end of the input by typing the special value -
1.
sum = 0 count = 0
num=int(input("Enter your number:"))
while num != -1:
sum = sum + num count =
count + 1
num =int(input("enter your number:"))
print ("Count is :", count)
print ("Sum is :", sum)
print ("Average is :", sum / count)

The for Loop


A for loop iterates through each statements in a sequence for exactly know many times the loop body needs
to be executed, so a control variable can be used to count the executions. A loop of this type is called
a counter-controlled loop. In general, the loop can be written as follows:
for i in range(initialValue, endValue):
# Loop body #Note that the statement(s) must be indented
In general, the syntax of a for loop is:
for var in sequence:
# Loop body
The function range(a, b) returns the sequence of integers a, a + 1, ..., b-2, and b- 1. The range function has
two more versions. You can also use range(a) or range(a, b, k). range(a) is the same as range(0, a). k is
used as step value in range(a, b, k). The first number in the sequence is a. Each successive number
in the sequence will increase by the step value k. b is the limit. The last number in the sequence
must be less than b.

Example1:To demonstrate For


for i in range(5):
print (i)

Example2:
str=input("Enter a string")
for ch in str:
if ch in 'aeiou':
print ('letter', ch, 'is a vowel')
else:
print ('letter ', ch, 'is not a vowel')
Output of example2

We can iterate through a list by using for: Example3


for x in ['one', 'two', 'three', 'four']:
print(x)
This will print out the elements of the list:
one two
three four

Iterating over dictionaries:


Considering the following dictionary:
d = {"a": 1, "b": 2, "c": 3}
#To iterate through its keys, we can use:
for key in d:
print(key)Output:
Output:
"a" "b" "c"

Break and Continue in Loops


break statement:
When a break statement executes inside a loop, control flow comes out of the loop immediately:
Example:to demonstrate break
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1

The loop conditional will not be evaluated after the break statement is executed. Note that break
statements are only allowed inside loops. A break statement inside a function cannot be used to
terminate loops that called that function.
Executing the following prints every digit until number 4 when the break statement is
met and the loop stops:
Output
01234
Breaking from loop
Break statements can also be used inside for loops, the other looping construct provided by
Python:
Example:
for i in (0, 1, 2, 3, 4):
print(i)
if i == 2:
break
Executing this loop now prints:
012
Note that 3 and 4 are not printed since the loop has ended.

Continue statement
A continue statement will skip to the next iteration of the loop bypassing the rest of the current
block but continuing the loop. Continue can only used inside loops:

Example to demonstrate continue


for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
Note that 2 and 4 aren't printed, this is because continue goes to the next iteration instead of continuing
on to print(i) when i == 2 or i == 4.
Executing this loop now prints:
0135
The Pass
The pass statement is used in code in places where the language requires a statement to appear
but we wish the program to take no action. We can make the code fragment legal by adding a pass statement:
if x < 0:
pass # Do nothing else:
print(x)
Pass is a null statement, when a statement is required by Python syntax (such as within the
body of a for or while loop), but no action is required or desired by the programmer. This can be useful
as a placeholder for code that is yet to be written.
Example: to demonstrate pass
for x in range(10):
pass #we don't want to do anything, so we'll pass
In this example, nothing will happen. The for loop will complete without error, but no commands or
code will be actioned. Pass allows us to run our code successfully without having all commands
and action fully implemented. Similarly, pass can be used in while loops, as well as in selections and
function definitions etc.

Nested Loops
A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner
loops. Each time the outer loop is repeated; the inner loops are re- entered and started a new. Below is
classical example for nesting of loops.
Example: Multiplcationtable
print(" Multiplication Table")
# Display the number title print("
|", end = '')
for j in range(1, 10):
print(" ", j, end = ' ') print() # Jump to the new line
print("——————————————————————————————————————————")
# Display table body for i in
range(1, 10):
print(i, "|", end = '')
# Display the product and align properly for j
in range(1, 10):
print(format(i * j, "4d"), end = '')
print() # Jump to the new line
Output

FUNCTIONS
 A function is a collection of statements grouped together that performs an operation.
 A function is a way of packaging a group of statements for later execution.
The function is given a name. The name then becomes a short-hand to
describe the process. Once defined, the user can use it by the name, and not by the steps
involved. Once again, we have separated the “what” from the “how”, i.e. abstraction.
Functions in any programming language can fall into two broad categories:
 Built-in functions
They are predefined and customized, by programming languages and each serves a specific purpose.
 User-defined functions
They are defined by users as per their programming requirement.
There are two sides to every Python function:
• Function definition. The definition of a function contains the code that determines
the function’s behaviour.
• Function call. A function is used within a program via a function invocation.
Defining a Function
A function definition consists of the function’s name, parameters, and body.
The syntax for defining a function is as follows:
def functionName(list of parameters):
Statements # Note that the statement(s) must be indented return

 A function contains a header and body. The header begins with the def keyword, followed by the
function’s name known as the identifier of the function and parameters, and ends with a colon.
 The variables in the function header are known as formal parameters or simply parameters. When a
function is invoked, you pass a value to the parameter. This
value is referred to as an actual parameter or argument. Parameters are optional;
that is, a function may not have any parameters.
 Statement(s) – also known as the function body – are a nonempty sequence of
statements executed each time the function is called. This means a function body cannot be empty,
just like any indented block.
 Some functions return a value, while other functions perform desired operations without returning a
value. If a function returns a value, it is called a value- returning function.
Calling a Function
Calling a function executes the code in the function. In a function’s definition, you define what
it is to do. To use a function, you have to call or invoke it. The program that calls the function is
called a caller. There are two ways to call a function, depending on whether or not it returns a
value. If the function returns a value, a call to that function is usually treated as a value.

For example,
larger = max(3, 4)
Calls max(3, 4) and assigns the result of the function to the variable larger.
Another example of a call that is treated as a value is
print(max(3, 4))
This prints the return value of the function call max (3, 4).

Example:
# Return the max of two numbers
# Function with arguments and return def
max(num1, num2):
if num1 > num2:
result = num1 else:
result = num2
return result def
main():
i = 5
j = 2
k = max(i,j)# Call the max function
print("The larger number of", i, "and", j, "is", k)
main() # Call the main function
Output
The larger number of 5 and 2 is 5
Categories of User-defined functions
1. Function with arguments
2. Function with an argument and return type
3. Function with default argument
4. Function with variable length argument
5. Pass by reference.
Function with arguments
A function can contain any number of arguments depending on the requirement.
Example:
def func(passArgument):#function definition print
passArgument
str = "Hello all" func(str)#
function call
In this example, the func function accepts one argument which has a data type string. We create
a variable str with a certain string statement assigned and then we call
the func function and thereby pass the value of str. Finally, the output
will be:
Hello all
Function with an argument and return type
This type of function takes any arbitrary number of arguments and return
specific data type or value from it.
Example: Refer above program Fun_max.py
Function with default argument
In this type of function, the formal parameter assigned with some value, represents a
default parameter or default argument. If the caller does not supply an actual parameter, the formal
parameter value is assigned.
Example:
def info(name, age=50):
print("Name:", name)
print("Age:", age)
info("John", age=28)
info("James")
Output: Name: John
Age: 28
Name: James
Age: 50
Function with variable length argument
There might be a scenario where you need to pass more arguments than specified during the function
definition. In this case, variable length arguments can be passed:
Syntax
def function_name(arg, *var):
code block return
Here, arg means normal argument which is passed to the function. The *var refers to
the
variable length argument.
Example:
def variable_argument( arg, *vari):
print ("Out-put is",arg)
for var in vari:
print (var)
variable_argument(60)
variable_argument("Hari",100,90,40,50,60)
Output:Out-put is 60
Out-put is Hari
100
90
40
50
60
>>>

Pass by reference versus pass by value


In pass by reference values to the argument of the function are passed as reference, that is, the address
of the variable is passed and then the operation is done on the value stored at these addresses.
Pass by value means that the value is directly passed as the value to the argument of the function. In
this case, the operation is done on the value and then the value is stored at the address.
In Python arguments, the values are passed by reference. During the function call, the called function uses
the value stored at the address passed to it and any changes to it also affect the source variable:

Example: call by reference


def pass_ref(list1):#Call by ref
list1.extend([23,89])
print ("list inside the function: ",list1)

list1 = [12,67,90]
print ("list before pass", list1)
pass_ref(list1)
print ("list outside the function", list1)

Output:
list before pass [12, 67, 90]
list inside the function: [12, 67, 90, 23, 89]
list outside the function [12, 67, 90, 23, 89]
Here, in the function definition, we pass the list to the pass_ref function and then we extend the list to
add two more numbers to the list and then print its value. The list extends inside the function, but
the change is also reflected back in the calling function. We finally get the output by printing out
different representations of the list: Let's look at another Example:
def func(a):#call by value function a=a+4
print ("Inside the function", a)

a= 10 func(a)
print ("Outside the function", a)
The preceding example call by value, as the change happening inside the Python
function does not get reflected back in the calling function. It is still a pass by reference, as, in
this situation inside the function, we made new assignment, that is, a= a+4. Although you might think
that a = a + 4 is changing the number stored in a, but it is actually reassigning a to point to a new value:
Returning Multiple Values from a Function
In python function, we can return multiple values. We can use return statements as
return a,b,c
Here a,b,c values returned by function as tuples and we have to use three variables to receive these
values in called function as shown below
X,Y,Z=function()
Example:sum_sub_mul
def Sum_Sub_Mul(a,b):
sum=a+b sub=a-b
mul=a*b
return sum,sub,mul def
main():
a=10 b=5
X,Y,Z=Sum_Sub_Mul(a,b) print("Sum
of two no=",X) print("Sub of two
no=",Y) print("Mul of two no=",Z)
print("Sum, Sub and Mul of two no:")
T=Sum_Sub_Mul(a,b)#Retrieving multiple value using Tuples for i
in T:
print(i,end='\n ')
main()
Output
Sum of two no= 15
Sub of two no= 5
Mul of two no= 50
Sum, Sub and Mul of two no:
15
5
50
>>>
Local and Global Variables
When we declare variable inside a function it becomes a local variable and its scope is limited to that
function where it is created and it is available in that function and not available outside the function.
When a variable declared outside the function, it is available to all function which are using these
variables.
Sometimes local variable and global variable have the same name, in this case the function ignores
global variable and uses local variable only.
When the programmer wants to use the global variable inside a function, we can use the keyword global
before the variable in the beginning of the function body.

Example:
b=20#global variable c=30
def myfunction(): a=10#Local
variable print("Global
B:",b) print("Local A:",a)
global c#This is global c
print("Global C:",c) c=50#this is
local c print("Local C:",c)
myfunction()
Output
Global B: 20
Local A: 10
Global C: 30
Local C: 50
>>>

RECURSION
A recursive function is one that invokes itself. Or A recursive function is a function that calls
itself in its definition.
For example the mathematical function, factorial, defined by factorial(n) = n*(n-1)* (n-2)*...*3*2*1. can
be programmed as
def factorial(n):
#n here should be an integer
if n == 0:
return 1
else:
return n*factorial(n-1)

Any recursive function can be divided into two parts.


First, there must be one or more base cases, to solve the simplest case, which is referred to as the
base case or the stopping condition
Next, recursive cases, here function is called with different arguments, which are
referred to as a recursive call. These are values that are handled by “reducing” the problem to a
“simpler” problem of the same form.
Example: To find factorial using Recursion
def main():
n=int(input("Enter a nonnegative integer: "))
print("Factorial of", n, "is",factorial(n)) print("
0! = ", factorial(0))
print(" 1! = ", factorial(1))
print(" 5! = ", factorial(6))
# Return the factorial for the specified number def
factorial(n):
if n == 0: # Base case return
1
else:
return n*factorial(n-1) # Recursive call main()#
call the main
Output:
Enter a nonnegative integer: 5
Factorial of 5 is 120
0! = 1
1! = 1
5! = 720

PROFILING
Profiling means having the application run while keeping track of several different parameters, like the
number of times a function is called, the amount of time spent inside it, and so on. Profiling can help
us find the bottlenecks in our application, so that we can improve only what is really slowing us down.
Python includes a profiler called cProfile. It breaks down your entire script and for each method in
your script it tells you:

ncalls: The number of times a method was called


tottime: Total time spent in the given function (excluding time made in calls to sub- functions)
percall: Time spent per call. Or the quotient of tottime divided by ncalls
cumtime: The cumulative time spent in this and all subfunctions (from invocation till exit). This figure is
accurate even for recursive functions.
percall: is the quotient of cumtime divided by primitive calls
filename: lineno(function): provides the respective data of each function
MODULES
A module is a library of functions. Modules are code files meant to be used by other
programs. Normally files that are used as modules contain only class and function definitions.
Modularizing makes code easy to maintain and debug, and enables the code to be reused. To use a
module, we use the import statement. A module can also import other modules.
Example:GCD_LCM
# File name GCD_LCM_Module.py
# Return the gcd of two integers def
gcd(n1, n2):
p = n1 # Initial gcd is 1 q= n2 #
Possible gcd
while n2!=0:
r=n1%n2 n1=n2
n2=r
gcd=n1
lcm=int(p*q/gcd)
return gcd,lcm # Return gcd and lcm

Now we write a separate program to use the above module function, as shown below
File name Test_module
# file name Test_module.py
from GCD_LCM_Module import gcd # Import the module
# Prompt the user to enter two integers
n1 = eval(input("Enter the first integer: "))
n2 = eval(input("Enter the second integer: "))
print("The GCD and LCM for", n1,"and", n2, "is", gcd(n1, n2))
Output:
Enter the first integer: 6
Enter the second integer: 3
The GCD and LCM for 6 and 3 is (3, 6)
>>>
The import statement
In order to use the functions and variables of the module1.py program, we will use the import statement.
The syntax of the import statement is shown here:
import module1, module2, module
The statements and definitions of modules are executed for the first time when the interpreter
encounters the module name in the import statement.
In preceding code, in order to use the module variables and functions, use the
module_name.variable and module_name.function() notations.
In order to write module1 with every function of module1.py, Python allows use
the as statement as shown. The syntax is given as follows:
import module_name as new_name
Example:module
def sum1(a,b):
c = a+b
return c def
mul1(a,b):
c = a*b return c
Filename:Test_module
import module1 #import module_name x = 12
y = 34
print ("Sum is ", module1.sum1(x,y))
print ("Multiple is ", module1.mul1(x,y))

Filename:Test_module2.py
import module1 as md #import module_name as new_name x = 12
y = 34
print ("Sum is ", md.sum1(x,y))
print ("Multiple is ", md.mul1(x,y))

ARRAY, LISTS, SETS AND DICTIONARY Arrays


An array is a data structure that stores values of same data type. In Python, this is the main difference
between arrays and lists.
While python lists can contain values corresponding to different data types, arrays in python can only
contain values corresponding to same data type.
To use arrays in python language, you need to import the standard array module. This is because array is
not a fundamental data type like strings, integer etc. Here is how you can import array module in python:
from array import *
Once you have imported the array module, you can declare an array. Here is how you do it:
arrayIdentifierName = array(typecode, [Initializers])

Typecode Details

B Represents signed integer of size 1 byte

B Represents unsigned integer of size 1 byte

C Represents character of size 1 byte

u Represents unicode character of size 2 bytes

h Represents signed integer of size 2 bytes


H Represents unsigned integer of size 2 bytes
i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

w Represents unicode character of size 4 bytes

1 Represents signed integer of size 4 bytes

L Represents unsigned integer of size 4 bytes

f Represents floating point of size 4 bytes

D Represents floating point of size 8 bytes

Example of an array containing 5 integers:


from array import *
my_array = array('i', [1,2,3,4,5])
for i in my_array:
print(i)
#output:1,2,3,4,5
Some built-in array methods:
Append any value to the array using append() method my_array =
array('i', [1,2,3,4,5]) my_array.append(6)
# array('i', [1, 2, 3, 4, 5, 6])
Note that the value 6 was appended to the existing array values.

Insert value in an array using insert() method my_array =


array('i', [1,2,3,4,5])
my_array.insert(0,0)
#array('i', [0, 1, 2, 3, 4, 5])
In the above example, the value 0 was inserted at index 0. Note that the first argument
is the index while second argument is the value.
Extend python array using extend() method my_array =
array('i', [1,2,3,4,5]) my_extnd_array =
array('i', [7,8,9,10])
my_array.extend(my_extnd_array)
# array('i', [1, 2, 3, 4, 5, 7, 8, 9, 10])
We see that the array my_array was extended with values from my_extnd_array.

Remove any array element using remove() my_array =


array('i', [1,2,3,4,5]) my_array.remove(4)
# array('i', [1, 2, 3, 5])
We see that the element 4 was removed from the array.

Remove last array element using pop() method


pop removes the last element from the array.
my_array = array('i', [1,2,3,4,5])
my_array.pop()
# array('i', [1, 2, 3, 4])
So we see that the last element (5) was popped out of array.

Fetch any element through its index using index()


index() returns first index of the matching value. Remember that arrays are zero- indexed.
my_array = array('i', [1,2,3,4,5])
print(my_array.index(5))
#output: 5
my_array = array('i', [1,2,3,3,5])
print(my_array.index(3))
#output: 3
Note in that second example that only one index was returned, even though the value
exists twice in the array

Reverse a python array using reverse() method


The reverse() method reverses the array.
my_array = array('i', [1,2,3,4,5])
my_array.reverse()
# array('i', [5, 4, 3, 2, 1])
Sort a python array using sort() method
from array import * my_array =
[1,20,13,4,5] my_array.sort()
print(my_array)
#output:1,4,5,13,20

Multi-Dimensional Array
An array containing more than one row and column is called multidimensional array. It is also
called combination of several 1D arrays.2D array is also considered as matrix.

A=array([1,2,3,4])# create 1D array with 1 row


B=array([1,2,3,4],[5,6,7,8]) create 2D array with 2 row
Example:2D_array

from numpy import* a=array([[1,2,3],[4,5,6],


[7,8,9]]) print(a)#Prints 2D array as rows
print("2D Array Element wise Printing") for i
in range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=' ')#Prints array element wise
print(end='\n')
print(end='\n' )
#2D array As matrix by using matrix fun
print("Matrix printing")
a=matrix('1 2 3; 4 5 6 ; 7 8 9')
print(a)
Output
[[1 2 3] [4 5 6]
[7 8 9]]
2D Array Element wise Printing
1 2 3
4 5 6
7 8 9
Matrix printing
[[1 2 3] [4 5 6]
[7 8 9]]
>>>

Matrix in Numpy
In python we can show matrices as 2D array. In numpy, a matrix is considered as specialized 2D
array. It has lot of built in operators on 2D matrices. In numpy, matrix is created using the following
syntax.
Matrix_name=matrix(2D array or string)
Eg. a=matrix('1 2 3;4 5 6;7 8 8')

Matrix addition, multiplication and division.


We can use arithmetic operators like +, -,* ,/ to perform different operations on matrices.
Example: Matrix_Operation
from numpy import*
a=matrix('4 4 4;4 4 4;4 4 4')
b=matrix('2 2 2;2 2 2;2 2 2')
print("Printing A matrix") print(a)
print("Printing B matrix")
print(b)
print("Printing Addition of two matrix")
c=a+b #matrix addition
print(c)
print("Printing Multplication of two matrix")
c=a*b #matrix addition
print(c)
print("Printing Division of two matrix")
c=a/b #matrix addition print(c) Output
Printing A matrix
[[4 4 4]
[4 4 4] [4 4 4]]
Printing B matrix
[[2 2 2] [2 2 2] [2 2 2]]
Printing Addition of two matrix
[[6 6 6] [6 6 6]
[6 6 6]]
Printing Multplication of two matrix
[[24 24 24] [24 24
24] [24 24 24]]
Printing Division of two matrix
[[2. 2. 2.] [2. 2.
2.] [2. 2. 2.]]
>>>
Example: #prog to accept matrix from key board and display its transpose.
from numpy import*
# Accept Rows and Column of matrix")
r,c=[int(a) for a in input("Enter rows,col:").split()]
str=input("Enter matrix elements:")
#convert the string into amatrix with size r*c
x=reshape(matrix(str),(r,c))
print("The original matrix")
print(x)
print("Printing Transpose of matrix")
y=x.transpose()
print(y) Output

LISTS
Enter rows,col: 2 2
Enter matrix elements:1 2 3 4
The original matrix
[[1 2] [3 4]]
Printing Transpose of matrix
[[1 3]
[2 4]]
>>>
A list is an object that holds a collection of objects; it represents a sequence of data. A list can hold
any Python object. A list need not be homogeneous; that is, the elements of a list do not all have to be of
the same type.
Like any other variable, a list variable can be local or global, and it must be defined
(assigned) before its use.
The following are the characteristics of a Python list:
 Values are ordered
 Mutable
 A list can hold any number of values
 A list can add, remove, and alter the values

Creating a list
Let's see how we can create an empty list:
<Variable name > = [ ] E.g.
List1 = [ ] Creating a list with
values
A list contains comma-separated values. For example:
a = [1, 2, 3, 4, 5]
Avengers = ['hulk', 'iron-man', 'Captain', 'Thor']

List methods and supported operators


Starting with a given list a:
a = [1, 2, 3, 4, 5]
1. append(value) – appends a new element to the end of the list.
# Append values 6, 7, and 7 to the list
a.append(6)
a.append(7)
a.append(7)
# a: [1, 2, 3, 4, 5, 6, 7, 7]
# Append an element of a different type, as list elements do not need to have
the same type
my_string = "hello world"
a.append(my_string)
# a: [1, 2, 3, 4, 5, 6, 7, 7, [8, 9], "hello world"]
Note that the append() method only appends one new element to the end of the
list. If you append a list to another list, the list that you append becomes a single element at the end of
the first list.
# Appending a list to another list a = [1,
2, 3, 4, 5, 6, 7, 7]
b = [8, 9]
a.append(b)
# a: [1, 2, 3, 4, 5, 6, 7, 7, [8, 9]]
a[8]
# Returns: [8, 9]
2. extend(enumerable) – extends the list by appending elements from another
enumerable.
a = [1, 2, 3, 4, 5, 6, 7, 7]
b = [8, 9, 10]
# Extend list by appending all elements from b
a.extend(b)
# a: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]
# Extend list with elements from a non-list enumerable:
a.extend(range(3))
# a: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10, 0, 1, 2]
Lists can also be concatenated with the + operator. Note that this does not
modify any of the original lists:
a = [1, 2, 3, 4, 5, 6] + [7, 7] + b
# a: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]
3. index(value, [startIndex]) – gets the index of the first occurrence of the input
value. If the input value is not in the list a ValueError exception is raised. If a second argument is
provided, the search is started at that specified index.
a.index(7)
# Returns: 6
a.index(49) # ValueError, because 49 is not in a.
a.index(7, 7)
# Returns: 7
a.index(7, 8) # ValueError, because there is no 7 starting at index 8
4. insert(index, value) – inserts value just before the specified index. Thus after the
insertion the new element occupies position index. a.insert(0, 0) #
insert 0 at position 0
a.insert(2, 5) # insert 5 at position 2
# a: [0, 1, 5, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]
5. pop([index]) – removes and returns the item at index. With no argument it removes
and returns the last element of the list.
a.pop(2)
# Returns: 5
# a: [0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]
a.pop(8)
# Returns: 7
# a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# With no argument:
a.pop()
# Returns: 10
# a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6. remove(value) – removes the first occurrence of the specified value. If the provided
value cannot be found, a ValueError is raised.
a.remove(0)
a.remove(9)
# a: [1, 2, 3, 4, 5, 6, 7, 8]
a.remove(10)
# ValueError, because 10 is not in a
7. reverse() – reverses the list in-place and returns None.
a.reverse()
# a: [8, 7, 6, 5, 4, 3, 2, 1]
8. count(value) – counts the number of occurrences of some value in the list.
a.count(7)
# Returns: 2
9. sort() – sorts the list in numerical and lexicographical order and returns None.
a.sort()
# a = [1, 2, 3, 4, 5, 6, 7, 8]
# Sorts the list in numerical order
10. The slicing of a list. Syntax: <list-name> [start: stop: step]
a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[2:5]) #Output:[3, 4, 5]
Example:#to demonstrate lists
NUMBER_OF_ELEMENTS = 5
# Create an empty list
numbers=[]
sum = 0
for i in range(NUMBER_OF_ELEMENTS):
value = eval(input("Enter a new number: "))
numbers.append(value)
sum += value
average = sum / NUMBER_OF_ELEMENTS
count = 0 # The number of elements above average for i
in range(NUMBER_OF_ELEMENTS):
if numbers[i] > average:
count += 1 print("Average
is", average)
print("Number of elements above the average is", count)
numbers.append(value)

Multidimensional Lists
Data in a table or a matrix can be stored in a two-dimensional list. A two- dimensional list is a list
that contains other lists as its elements.
A value in a two-dimensional list can be accessed through a row and column index. You can think of a two-
dimensional list as a list that consists of rows. Each row is a list that contains the values. The rows can be
accessed using the index, conveniently called a row index. The values in each row can be accessed through another
index, called a column index.
A two-dimensional list named matrix is illustrated in Figure.

Example: Initializing Lists with Input Values:


#The following loop initializes the matrix with user input values:
matrix = [] # Create an empty list
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter the number of columns: "))
for row in range(numberOfRows):
matrix.append([]) # Add an empty new row for
column in range(numberOfColumns):
value = eval(input("Enter an element and press Enter: "))
matrix[row].append(value)
print("Printing Matrix....")
for row in range(len(matrix)):
for column in range(len(matrix[row])):
print(matrix[row][column], end = " ")
print() # Print a new line
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter an element and press Enter: 1
Enter an element and press Enter: 2
Enter an element and press Enter: 3
Enter an element and press Enter: 4
Printing Matrix....
1 2
3 4
>>>

SETS
lists,
Sets are like lists in that you use them for storing a collection of elements. Unlike the elements in a set are
non-duplicates and are not placed in any particular order.

Creating Sets
Python provides a data structure that represents a mathematical set. As with mathematical sets,
elements of Set are enclosed inside a pair of curly braces ({ }). The
elements are non-duplicate, separated by commas. You can create an empty set, or you can create a set from a
list or a tuple, as shown in the following examples:
s1 = set( ) # Create an empty set
s2 = {1, 3, 5} # Create a set with three elements s3 = set([1, 3, 5])
# Create a set from a tuple

Example: Program to convert Tuple into Set:


#We can make a set out of a list using the set conversion
function:
L = [10, 13, 10, 5, 6, 13, 2, 10, 5]
S=set(L)
print(L)
print(S)
{10, 2, 13, 5, 6}

Example: Operations on Sets: s1 = {1, 2,


4} s1.add(6)
print(s1)#prints {1, 2, 4, 6}
print(len(s1))
#prints 4
print(max(s1))
#prints 6
print(min(s1))
#prints 1 print(sum(s1))
#prints 13 print(3 in
s1)
#prints False
s1.remove(4)
print(s1)
#prints {1,2,6)
s1 = {1, 2, 4}
s2 = {1, 4, 5, 2, 6}
print(s1.issubset(s2)) # s1 is a subset of s2
#prints True
s1 = {1, 2, 4}
s2 = {1, 4, 5, 2, 6}
print(s2.issuperset(s1)) # s2 is a superset of s1
#prints True
s1 = {1, 2, 4}
s2 = {1, 4, 2}
print(s1 == s2)#prints True
print(s1 != s2)#prints False

Set Operations
Python provides the methods for performing set union, intersection, difference, and symmetric difference
operations.
Example:
s1 = {1, 4, 5, 6} s2 = {1, 3, 6,
7} print(s1.union(s2)) print(s1 |
s2) print(s1.intersection(s2))
print(s1 & s2)
print(s1.difference(s2)) print(s1
- s2)
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
Output:
{1, 3, 4, 5, 6, 7}
{1, 3, 4, 5, 6, 7}
{1, 6}
{1, 6}
{4, 5}
{4, 5}
{3, 4, 5, 7}
{3, 4, 5, 7}
>>>
DICTIONARIES
A dictionary is a container object that stores a collection of key/value pairs. It enables
fast retrieval, deletion, and updating of the value by using the key.
A dictionary is a collection that stores the values along with the keys. The keys are like an index
operator. In a list, the indexes are integers. A dictionary cannot contain duplicate keys. Each key
maps to one value. A key and its corresponding value form an item (or entry) stored in a
dictionary, as shown in Figure. The data structure is a called a “dictionary” because it
resembles a word dictionary, where the words are the keys and the words’ definitions is the
values. A dictionary is also known as a map, which maps each key to a value.

The syntax of a dictionary is as follows:


Dictionary_name = {key: value}

Example:
port = {22: "SSH", 23: "Telnet" , 53: "DNS", 80: HTTP" } The
port variable refers to a dictionary that contains port
numbers as keys and its protocol names as values.
Consider the following example:
Companies = {"IBM": "International Business
Machines", "L&T" :"Larsen & Toubro"}

Characteristics of dictionary:
 The keys in a dictionary may have different types(string, int, or float)
 The values in a dictionary may have different types
 The values in a dictionary may be mutable objects
 The key of the dictionary cannot be changed i.e. Keys are unique
 Values can be anything, for example, list, string, int, and so on
 Values can be repeated
 Values can be changed
 A dictionary is an unordered collection, which means that the order in which you have entered
the items in a dictionary may not be retained and you may get the
items in a different order i.e. the order of key: value pairs in a dictionary are
independent of the order of their insertion into the dictionary
Operations on the dictionary
A dictionary is mutable; we can add new values, and delete and update old values.
Accessing the values of dictionary
The dictionary's values are accessed by using key. Consider a dictionary of networking ports: In
order to access the dictionary's values, the key is considered.
Port = {80: “HTTP”, 23: “Telnet”, 443: “HTTPS”}
print(port[80])
>>'HTTP'
print(port[443])
>>'HTTPS'
If the key is not found, then the interpreter shows the preceding error.

Deleting an item from the dictionary


del keyword is used to delete the entire dictionary or the dictionary's items.
Syntax to delete dictionary’s item:
del dict[key]
Considering the following code snippet for example:
>>> port = {80: "HTTP", 23 : "Telnet", 443 : "HTTPS"}
>>> del port[23]
>>> print(port)
{80: 'HTTP', 443: 'HTTPS'}
>>>
Syntax to delete the entire dictionary:
del dict_name
Consider the following example:
>>> port = {80: "HTTP", 23 : "Telnet", 443 : "HTTPS"}
>>> del port
>>> print(port)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
port
NameError: name 'port' is not defined
>>>
The preceding error shows that the port dictionary has been deleted.
Updating the values of the dictionary
To update the dictionary, just specify the key in the square bracket along with the dictionary
name and assigning new value. The syntax is as follows:
dict[key] = new_value
Example:
port = {80: "HTTP", 23 : "SMTP”, 443 : "HTTPS"}
In the preceding dictionary, the value of port 23 is "SMTP", but in reality, port number
23 is for telnet protocol. Let's update the preceding dictionary with the following code:
>>> port = {80: "HTTP", 23 : "SMTP", 443 : "HTTPS"}
>>>print( port)
{80: 'HTTP', 443: 'HTTPS', 23: 'SMTP'}
>>> port[23] = "Telnet"
>>> print(port)
{80: 'HTTP', 443: 'HTTPS', 23: 'Telnet'}
>>>
Adding an item to the dictionary
Item can be added to the dictionary just by specifying a new key in the square brackets along
with the dictionary. The syntax is as follows:
dict[new_key] = value
Example:
>>> port = {80: "HTTP", 23 : "Telnet"}
>>> port[110]="POP"
>>> print(port)
{80: 'HTTP', 110: 'POP', 23: 'Telnet'}
>>>
Other dictionary functions:
Similar to lists and tuples, built-in functions available for dictionary.
len()- to find the number of items that are present in a dictionary.
Example:
>>> port = {80: "http", 443: "https", 23:"telnet"}
>>> print(len(port))
3
>>>
max()-It returns the key with the maximum worth.
Example:
>>> dict1 = {1:"abc",5:"hj", 43:"Dhoni", ("a","b"):"game", "hj":56}
>>> max(dict1) ('a',
'b')
min()- It returns the dictionary's key with the lowest worth. The syntax of the method
is as follows:
Example:
>>> dict1={1: 'abc', (1, 3): 'kl', 5: 'hj', 43: 'Dhoni', 'hj':
56}
>>> min(dict1)
1
>>>

FILES

Files are used to store data permanently. Data used in a program is temporary; unless the data is
specifically saved, it is lost when the program terminates. To permanently store the data created in a
program, you need to save it in a file on a disk or some other permanent storage device. The file can be
transported and can be read later by other programs.

Python’s standard library has a file class that makes it easy for programmers to make
objects that can store data to, and retrieves data from, disk

In order to read and write into a file, we will use the open() built-in function to open the file. The
open() function creates an file_object object.
The Syntax is:

file_object = open(file_name ,access_mode)

The first argument,file_name, specifies the filename that is to be opened. The second argument,
access_mode, determines in which mode the file has to be opened, that is, read, write and append.
Mode Description

"r" Opens a file for reading.

"w" Opens a new file for writing. If the file already exists, its old
contents are destroyed.

"a" Opens a file for appending data from the end of the file.

"rb" Opens a file for reading binary data.

"wb" Opens a file for writing binary data.

"r+" Opens a file for reading and writing.


"w+" Opens a file for reading and writing. If the file doesn't exist, then a
new file is created.

Examples:
f = open('myfile.txt', 'r')
Creates a file object named f capable of reading the contents of the text file named myfile.txt. in
current directory.
f = open('myfile.txt', 'w')
Creates and returns a file object named f capable of writing data to the text file named
myfile.txt.
We can also use the absolute path to filename to open the file in Windows, as follows:
f = open(“c:\\pybook\\myfile.txt", "r")
Creates and returns a file object named f capable of reading data to the text file named myfile.txt
in folder name python in c drive
f = open('myfile.txt', 'a')
New data will be appended after the pre-existing data in that file.

Writing text to a file


The 'w' mode creates a new file. If the file already exists, then the file would be overwritten.
We will use the write() function.
Example:
file_input = open("motivation.txt",'w') file_input.write("Never give up\n")
file_input.write("Rise above hate\n") file_input.write("No body remember second
place") file_input.close()
Output:

Example: with access mode 'a'.


file_input = open("motivation.txt",'a')
file_input.write("Opens a file for appending data from the end of the
file")
file_input.close()
Output:

Reading Data
After a file is opened for reading data, you can use the read() method to read a
specified number of characters or all characters from the file and return them as a string, the readline()
method to read the next line, and the readlines() method to read all the lines into a list of strings.
Example to read data
def main():
#Open file for input
infile = open("motivation.txt", "r")
print("(1) Using read():")
print(infile.read())#read all data
infile.close() # Close the input file
# Open file for input
infile = open("motivation.txt", "r")
print("\n(2) Using read(number): ") s1
=infile.read(6)#reads character print(s1)
infile.close() # Close the input file
#Open file for input
infile = open("motivation.txt", "r")
print("\n(3) Using readline(): ") line1
=infile.readline()#reads line
print(repr(line1))
infile.close() # Close the input file
infile = open("motivation.txt", "r")
# Open file for input
infile = open("motivation.txt", "r") print("\n(4) Using
readlines(): ") print(infile.readlines() )#prints lines
to list infile.close() # Close the input file
main() # Call the main functionample:Read_file.py

EXCEPTION HANDLING
Exception handling enables a program to deal with exceptions and continue its normal execution.
The run-time exceptions immediately terminate a running program. Rather than terminating the
program’s execution, an executing program can detect the problem when it arises and possibly
execute code to correct the issue or soften it in some way. This chapter explores handling exceptions in
Python.
An error that occurs at runtime is also called an exception. The run-time exceptions immediately
terminate a running program. Python provides a standard mechanism called exception handling that
allows the program to catch the error and prompt the user to correct the issue or soften it in some way
This can be done using Python’s exception handling syntax.
The syntax for exception handling is to wrap the code that might raise (or throw) an exception in a try
clause, as follows:
try:
<body>
except <ExceptionType>:
<handler>
Here, <body> contains the code that may raise an exception. When an exception occurs, the rest of
the code in <body> is skipped. If the exception matches an
exception type, the corresponding handler is executed. <handler> is the code that
processes the exception.
Example:
def divide(a,b):
try:
c = a/b return c
except :
print ("Error in divide function")
print(divide(10,0))#function call

Output
Error in divide function
None
>>>
Common standard exception classes

Class Meaning

AttributeError Object does not contain the specified instance variable or method

ImportError When import statement fails to find a specified module or name

IndexError A sequence (list, string, tuple) index is out of range

KeyError Specified key does not appear in a dictionary

NameError Specified local or global name does not exist

TypeError Operation or function applied to an inappropriate type

ValueError Operation or function applied to correct type but inappropriate value

ZeroDivisionError Second operand of divison or modulus operation is zero

A try with multiple except clause


A try statement can have more than one except clause to handle different exceptions.
The statement can also have an optional else and/or finally statement, in a syntax like this:
try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>

The multiple excepts are similar to elifs. When an exception occurs, it is checked to match an
exception in an except clause after the try clause sequentially. If a match is found, the handler for the
matching case is executed and the rest of the except clauses are skipped.
Note that the <ExceptionType> in the last except clause may be omitted. If the exception does
not match any of the exception types before the last except clause, the
<handlerExcept> for the last except clause is executed.
A try statement may have an optional else clause, which is executed if no exception is raised in the try
body.
A try statement may have an optional finally clause, which is intended to define clean- up actions that
must be performed under all circumstances.

Ex : Multiple excepts
def main():
try:
number1, number2 = eval(input("Enter two numbers, separated by
a comma: ")) result =
number1 / number2 print("Result
is", result) except
ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input") else:
print("No exceptions") finally:
print("The finally clause is executed")
main() # Call the main function

Output

The try...finally statement


A try statement may include an optional finally block. Code within a finally block always executes
whether the try block raises an exception or not. A finally block usually contains “clean-up code”
that must execute due to activity initiated in the try block.
The syntax is as follows:
try:
#run this action first except:
# Run if exception occurs
Finally :
#Always run this code

The order of the statement should be:


try -> except -> else -> finally

Example: to demonstrate finally


def main():
try:
num = int(input("Enter the number "))
re = 100/num except:
print ("Something is wrong")
else:
print ("result is ",re)
finally :
print ("finally program ends")
main()
Output
Enter the number 15
result is 6.666666666666667 finally
program ends
>>>
MULTITHREADED PROGRAMMING
Computer programs are purely executable, binary (or otherwise), which reside on disk. They do not take on
a life of their own until loaded into memory and invoked by the
operating system. A process (sometimes called a heavyweight process) is a program in execution. Each
process has its own address space, memory, a data stack, and other
auxiliary data to keep track of execution. Process switching needs interaction with operating system.
The operating system manages the execution of all processes on the system, dividing the time fairly
between all processes.
Processes can also fork or spawn(give birth) new processes to perform other tasks, but each new process
has its own memory, data stack, etc., and cannot generally share information unless inter process
communication (IPC) is employed.

What Are Threads?


Threads (sometimes called lightweight processes) are similar to processes except that they all execute
within the same process, thus all share the same context. They can be thought of as "mini-processes"
running in parallel within a main process or "main thread."
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer
that keeps track of where within its context it is currently running. It can be pre-empted (interrupted)
and temporarily put on hold (also known as sleeping) while other threads are running—this is called
yielding.
Multiple threads within a process share the same data space with the main thread and can therefore
share information or communicate with each other more easily than if they were separate processes.
Threads are generally executed in a concurrent fashion, and it is this parallelism and data sharing
that enable the coordination of multiple tasks.
Naturally, threads are scheduled in such a way that they run for a little bit, then yield to other threads.
Throughout the execution of the entire process, each thread performs its own, separate tasks, and
communicates the results with other threads as necessary.
If two or more threads access the same piece of data, inconsistent results may arise because of the
ordering of data access. This is commonly known as a race condition. The thread libraries come with
synchronization functions which allow the thread manager to control execution and access.
Some threads may not be given equal and fair execution time. This is because some functions block until
they have completed.
Multithreading, is the ability of a CPU to manage the use of operating system by executing multiple
threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into
multiple threads.

States of Thread
To understand the functionality of threads in depth, we need to learn about the lifecycle of the
threads or the different thread states. Typically, a thread can exist in five distinct states. The different
states are shown below:
New Thread
A new thread begins its life cycle in the new state. But, at this stage, it has not yet started and it has
not been allocated any resources. We can say that it is just an instance of an object.
Runnable
As the newly born thread is started, the thread becomes runnable i.e. waiting to run. In this state, it has
all the resources but still task scheduler have not scheduled it to run.
Running
In this state, the thread makes progress and executes the task, which has been chosen by task
scheduler to run. Now, the thread can go to either the dead state or the non-runnable/ waiting state.
Non-running/waiting
In this state, the thread is paused because it is either waiting for the response of some
I/O request or waiting for the completion of the execution of other thread.
Dead
A runnable thread enters the terminated state when it completes its task or otherwise terminates.

There are two different kinds of threads:


 Kernel threads
 User-space Threads or user threads
Kernel Threads are part of the operating system, while User-space threads are not implemented in the
kernel, can be seen as an extension of the function concept of a programming language.
Advantages of Threading:
 Multithreading improve the speed of computation on multiprocessor or multi-core
systems because each processor or core handles a separate thread concurrently.
 Multithreading allows a program to remain responsive while one thread waits for input and another runs
a GUI at the same time. This statement holds true for both
multiprocessor or single processor systems.
 All the threads of a process have access to its global variables. If a global variable changes in one thread,
it is visible to other threads as well. A thread can also have its
own local variables.

Disadvantages of Threading:
 On a single processor system, multithreading wouldn’t impact the speed of computation. In
fact, the system’s performance may downgrade due to the overhead of managing threads.
 Synchronization is required to avoid mutual exclusion while accessing shared resources of the
process. It directly leads to more memory and CPU utilization.
 Multithreading increases the complexity of the program thus also making it difficult to debug.
 It raises the possibility of potential deadlocks.
 It may cause starvation when a thread doesn’t get regular access to shared resources.
It would then fail to resume its work.
Creating threads in python
Python provides “Thread” class of threading module to create threads. We can create
threads in the following different ways.
 Creating threads without using a class
 Creating a thread by creating sub class to thread class
 Creating a thread without creating sub class to Thread class
Creating threads without using a class
In this method,a function is created and its name is passed as target for the thread as
t=Thread(target=function_name,[args=(arg1,arg2,..)
Here t is the object of thread class; the target represents the function on which the thread will
act.the args represents a tuple of arguments which are passed to the function. the tread is started by calling
the start() method as
t.start().
The thread t will execute the function.
Example:
import time
from threading import Thread

def sleepMe(i):
print("\nThread %i going to sleep for 5 seconds." % i)
time.sleep(5)
print("\nThread %i is awake now." % i)

for i in range(5):
th = Thread(target=sleepMe, args=(i, ))
th.start()
Output:
Thread 0 going to sleep for 5 seconds. Thread
1 going to sleep for 5 seconds. Thread 2 going
to sleep for 5 seconds. Thread 3 going to
sleep for 5 seconds. Thread 4 going to sleep
for 5 seconds.
>>>
Thread 4 is awake now. Thread
2 is awake now. Thread 1 is
awake now. Thread 3 is awake
now. Thread 0 is awake now.
Creating a thread by creating sub class to thread class
By using Thread class from threading module, we can create our own class as sub class to Thread class, so that we
can inherit the functionality of Thread class. By inheriting Thread class we can make use all methods of Thread
class into sub class. The Thread class has
run() method which is also available to sub class. Every thread will run this method when it is started. By
overriding this run we can make threads run our own run() method.

Example:
from threading import Thread import
time
class MyThread(Thread):
def run(self):
for i in range(1,6):
print("\nThread %i going to sleep for 5 seconds." %
i)
time.sleep(5)
print("\nThread %i is awake now." % i)
t1=MyThread()
t1.start() t1.join()

Output:
Thread 1 going to sleep for 5 seconds. Thread
1 is awake now.
Thread 2 going to sleep for 5 seconds.
Thread 2 is awake now.
Thread 3 going to sleep for 5 seconds. Thread
3 is awake now.
Thread 4 going to sleep for 5 seconds.
Thread 4 is awake now.
Thread 5 going to sleep for 5 seconds. Thread
5 is awake now.

Creating a thread without creating sub class to Thread class


We can ceate an independent class say MYThread that does not inherit from Thread class. Then
create object of MyThread .Next step is to create a thread by creating object to Thread class and
specifying the method of the My thread class as its target as
T1=Thread(target=obj.Sleep,args( ))
Example:
from threading import Thread import
time
class MyThread:
def Sleep(self):
for i in range(1,6):
print("Thread %i going to sleep for 5 seconds." % i)
time.sleep(5)
print("Thread %i is awake now." % i)
obj=MyThread()
t1=Thread(target=obj.Sleep())
t1.start()
Output:
Thread 1 going to sleep for 5 seconds. Thread
1 is awake now.
Thread 2 going to sleep for 5 seconds.
Thread 2 is awake now.
Thread 3 going to sleep for 5 seconds. Thread
3 is awake now.
Thread 4 going to sleep for 5 seconds. Thread
4 is awake now.
Thread 5 going to sleep for 5 seconds. Thread
5 is awake now
Thread synchronization
It is defined as a mechanism which ensures that two or more concurrent threads do not simultaneously
execute some particular program segment known as critical section.
Critical section refers to the parts of the program where the shared resource is accessed.
When a thread is already acting on an object, preventing any other thread from acting on the same
object is called is called thread synchronization. It is implemented using the following techniques:
 Locks
 Semaphores.

Locks are used to lock objects on which the thread is acting, after completion of execution, it will
unlock the object and comes out.
Locks is created by creating object of class Lock as shown below. L=Lock().
To lock the object,we should use the acquire() as L.axquire().
To unlock or release the object,release() method is used as L.release( )

*****
Chapter-3
Object Oriented Programming

The concept of object-oriented programming was seen to solve many problems, which procedural
programming did not solve. In object-oriented programming, everything is just like a real-world object.
In the real world, everything is an object. An object can have state and behavior. An object in the real
world can communicate with another object.
For example, a dog object in the real world has state and behavior. OOPS is based on
four pillars. They are:
Polymorphism Inheritance
Abstraction Encapsulation
Class and Objects
Key concepts
Class: A class defines the properties and behaviors for objects. Class is considered as a blueprint for
object creation. It provides a template for creating an object and specifying its behavior through
means of methods and state through means of variable instance name.
Objects: An object represents an entity in the real world that can be distinctly identified. An
object has a unique identity, state, and behavior or attributes. They can be considered as an instance of
a class. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
Inheritance: In object-oriented programming, the child class can inherit many
properties from the parent class. Here, the child class can use an existing method or behavior, which
the parent class has defined and use them accordingly in their class. Inheritance can be a single
inheritance or multiple inheritance. Single inheritance, as the name suggests, refers to only one
parent, while multiple inheritance refers to inheriting the property from multiple parents.
Polymorphism: In OOPs, an object can have many forms through means of different attributes. To
simplify, in our case, we can understand it by methods with the same name but having different outputs.
Abstraction: Here, we hide the necessary details and are only interested in showing the relevant details
to the other proposed user.
Encapsulation: This refers to hiding the necessary methods and their relevant details from the
outside world. A class can be treated as a best example, which
provides encapsulation to the methods and relevant instances.

Creating a class
Creating a class in Python is quite easy. Refer to the following syntax:
class <class name >(<parent class name>):#statements must be indented
<method definition-1>
<method definition-n>
Methods
The class functions are known by common name, methods. In Python, methods are defined as part of the
class definition and are invoked only by an instance. To call a
method we have to : (1) define the class (and the methods), (2) create an instance, and finally, (3)
invoke the method from that instance. Here is an example class with a method:
class MyMethod:#define the class
def display(self): # define the method print
('Welcome! to class MyMethod')
obj=MyMethod()
obj.display()
self is a parameter that references the object itself. Using self, you can access
object’s members in a class definition.
The self is a parameter that references the object itself. Using self, you can
access object’s members in a class definition. The self argument, which must be present in all
method invocations. That argument, represents the instance object, is passed to the method implicitly by
the interpreter when you invoke a method via an instance.
For example, you can use the syntax self.x to access the instance variable x and
syntax self.m1() to invoke the instance method m1 for the object self in a class .
To invoke the method we have to instantiate the class and call the method as follows.
>>> myObj = MyMethod() # create the instance
>>> myObj.display() # now invoke the method

Constructor (The init method)


Here init works as the class's constructor. When a user instantiates the class, it runs automatically.
A class provides a special method, __init . This method, known as an initializer, is invoked to
initialize a new object’s state when it is created. An initializer can perform any action, but initializers
are designed to perform initializing actions, such as creating an object’s data fields with initial values.
Python uses the following syntax to define a class:
class ClassName:
initializer methods
You can access the object’s data fields and invoke its methods by using the dot operator (.), also
known as the object member access operator.

Example: Construct1.py
import math class
Circle:
# Construct a circle object
def init (self, radius = 1):
self.radius = radius def
getPerimeter(self):
return 2 * self.radius * math.pi def
getArea(self):
return self.radius * self.radius * math.pi
def setRadius(self, radius):
self.radius = radius c =
Circle(5)
print(c.radius)
print(c.getPerimeter())
print(c.getArea())
c.setRadius(6) print(c.radius)
print(c.getPerimeter())
print(c.getArea())

Output:
5
31.41592653589793
78.53981633974483
6
37.69911184307752
113.09733552923255
Example: Construct2.py
class Car():
"""A simple attempt to represent a car.""" def
init (self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
def get_name(self):
"""Return a neatly formatted descriptive name."""
name = str(self.year) + ' ' + self.make + ' ' + self.model return
name
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_name())
Output:
2016 audi a4

Destructor ( del () Method )


Like constructor, there is an equivalent destructor special method called
del (). However, due to the way Python manages garbage collection of objects, this function is not
executed until all references to an instance object have been removed. Destructors in Python are
methods which provide special processing before instances are de_allocated and are not commonly
implemented since instances are rarely de_allocated explicitly.

Example:Destructor.py
class myClass:
count = 0 # use static data for count
def init (self): # constructor, incr. count
myClass.count = myClass.count + 1
def del (self): # destructor, decr. count
myClass.count = myClass.count - 1 def
howMany(self): # return count
return myClass.count
a = myClass() b =
myClass()
print(b.howMany())
print(a.howMany()) del b
print(a.howMany())
#print(b.howMany())Prints error after deletion of object b
Output:
2
2
1
Class variables
Class variables are the ones, which are sharable among all the instances of the class. The class
variable must be the same for all the instances.

Class Attributes
An attribute is a data or functional element which belongs to another object and is accessed via
the familiar dotted-attribute notation. Some Python types such as complex numbers have data attributes
(real and imag), while others such as lists and dictionaries have methods (functional attributes).

Class Data Attributes


Data attributes are simply variables of the class we are defining. They can be used like
any other variable in that they are set when the class is created and can be updated either by methods
within the class or elsewhere in the main part of the program.
Such attributes are better known to OO programmers as static members, class variables, or static
data. They represent data that is tied to the class object they belong to and are
independent of any class instances.

Class Methods Attributes


A method, in the class is simply a function defined as part of a class definition (thus making methods
class attributes). This means that Method applies only to objects (instances) of Class type. Note is tied
to its instance because invocation requires both names in the dotted notation:

Example:Class_var.py
class Tumkur_org():
mul_num = 1.20 #class variable
def init (self,first,last,pay):
self.f_name = first # Class Data Attributes
self.l_name = last self.pay_amt = pay
self.full_name = first+" "+last
def make_email(self): # Class Method Attributes
return self.f_name+ "."+self.l_name+"@gmail.com" def
increment(self):
self.pay_amt = int(self.pay_amt*self.mul_num)
return self.pay_amt
obj1 = Tumkur_org('Hari', 'Das', 60000)
obj2 = Tumkur_org('Mahesh', 'Span',70000)
print(obj1.full_name)# dotted notation
print(obj1.make_email()) print(obj1.increment())
print(obj2.full_name) print(obj2.make_email())
print(obj2.increment())

Output:
Hari Das
[email protected]
72000
Mahesh Span
[email protected]
84000

Inheritance
Inheritance in Python is based on similar ideas used in other object oriented languages like Java,
C++ etc. Inheritance allows us to inherit methods and attributes of the parent class. By inheritance, a
new child class automatically gets all of the methods and attributes of the existing parent class. The syntax
is given as follows:

class BaseClass(object):
pass

class DerivedClass(BaseClass):
<statement-1>
.
. .
<statement-N>
The BaseClass is the already existing (parent) class, and the DerivedClass is the new
(child) class that inherits (or subclasses) attributes from BaseClass.

OR
Inheritance enables you to define a general class (a superclass) and later extend it to more specialized
classes (subclasses).

Example:Simple_Inheritance.py
class Rectangle():
def init (self, w, h):
self.w = w self.h
= h
def area(self):
return self.w * self.h

class Square(Rectangle):
def init (self, l,b):
# call parent constructor.
super(). init (l, b)
self.L=l self.B=b
def perimeter(self):
return 2 * (self.L + self.B)
sqr=Square(5,6)
print(sqr.area())
print(sqr.perimeter())

The Square class will automatically inherit all attributes of the Rectangle class as well as the
object class.

super() refers to the superclass. Using super() we avoid referring the superclass explicitly.
super() is used to call the init ( ) method of Rectangle class, essentially calling any overridden
method of the base class. When invoking a method using super(), don’t pass self in the argument.

Types of Inheritance:
 Single Inheritance
 Multiple Inheritances
In Multiple inheritance a subclass inherited from more than one parent class and is able to access
functionality from both of them.
Syntax:
class A:
# variable of class A
# functions of class A

class B:
# variable of class A
# functions of class A

class C(A, B):


# class C inheriting property of both class A and B
# add more properties to class C

 Multilevel Inheritance class A:


# properties of class A

class B(A):
# class B inheriting property of class A
# properties of class B

class C(B):
# class C inheriting property of class B
# class C also inherits properties of class A
# properties of class C
Overriding methods
Overriding methods allows a user to override the parent class method. That is use the same method
both in base and child class. The name of the method must be the same in the parent class and the child
class with different implementations. Example:classover1.py:
class A():
def sum1(self,a,b): print("In
class A") c = a+b
return c class
B(A):
def sum1(self,a,b):
print("In class B")
c= a*a+b*b return
c
a_obj=A()
print(a_obj.sum1(4,5)) b_obj =
B() print(b_obj.sum1(4,5))
Output:
In class A
9
In class B
41
In the preceding example, classes A and B both have the same method sum1() with
different implementations.

Namespace
A namespace is mapping from names to objects. Examples are the set of built-in names (containing
functions that are always accessible for free in any Python program), the global names in a module,
and the local names in a function. Even the set of attributes of an object can be considered a namespace.
The namespaces allow defining and organizing names with clarity, without overlapping
or interference.
For example, the namespace associated with that book we were looking for in the library can be used to
import the book itself, like this:
from library.second_floor.section_x.row_three import book
We start from the library namespace, and by means of the dot (.) operator, we navigate
that namespace. Within this namespace, we look for second_floor, and
again we navigate with dot( .) operator. We then walk into section_x, and finally within the last
namespace, row_three, we find the name we were looking for: book.

Regular Expressions
● The Regular Expression Module A regular expression is a compact notation for representing a
collection of strings. What makes regular expressions so powerful is that a single regular expression
can represent an unlimited number of strings—
providing they meet the regular expression’s requirements. Regular expressions (which we will mostly
call “regexes” from now on) are defined using a mini-language that is completely different from Python—
but Python includes the re module through which we can seamlessly create and use regexes.★Regexes are
used for five main purposes:

• Parsing: identifying and extracting pieces of text that match certain criteria—regexes are used for
creating ad hoc parsers and also by traditional parsing tools

• Searching: locating substrings that can have more than one form, for example, finding any of
“pet.png”, “pet.jpg”, “pet.jpeg”, or “pet.svg” while avoiding “carpet.png” and similar

• Searching and replacing: replacing everywhere the regex matches with a string, for example, finding
“bicycle” or “human powered vehicle” and replacing either with “bike”

• Splitting strings: splitting a string at each place the regex matches, for example,
splitting everywhere colon-space or equals (“: ” or “=”) occurs
• Validation: checking whether a piece of text meets some criteria, for example, contains a
currency symbol followed by digits

The Python package


Python modules are a single file, whereas a Python package is a collection of modules.
A
package is a directory that contains Python modules. A package is a module that contains other
modules. Some or all of the modules in a package may be sub packages, resulting in a hierarchical
tree-like structure.

A namespace is mapping from names to objects. Examples are the set of built-in names (containing
functions that are always accessible for free in any Python program), the global names in a module,
and the local names in a function. Even the set of attributes of an object can be considered a namespace.
The namespaces allow defining and organizing names with clarity, without overlapping or interference.
For example, the namespace associated with that book we were looking for in the library can be used to
import the book itself, like this:
from library.second_floor.section_x.row_three import book
We start from the library namespace, and by means of the dot (.) operator, we navigate that namespace.
Within this namespace, we look for second_floor, and
again we navigate with dot( .) operator. We then walk into section_x, and finally within the last
namespace, row_three, we find the name we were looking for: book.

*****

Installing of python
 Python is well supported and freely available at https://www.python.org/downloads/
 Latest version : 3.8.5

3 PROBLEM SOLVING USING PYTHON UNIT-I

Python IDLE
 An Integrated Development Environment (IDLE) is a bundled set of software tools for program
development.
 An editor for creating and modifying programs
 A translator for executing programs
 A program debugger provides a means of taking control of the execution of a program to aid in
finding program errors
The Python Standard Library is a collection of modules, each providing specific functionality
beyond what is included in the core part of Python.
Python character set
 Letters: Upper case and lower case letters
 Digits: 0,1,2,3,4,5,6,7,8,9
 Special Symbols: Underscore (_), (,), [,], {,}, +, -, *, &, ^, %, $, #, !, Single quote(‘), Double
quotes(“), Back slash(\), Colon(:), and Semi Colon (;)
 White Spaces: (‘\t\n\x0b\x0c\r’), Space, Tab.
Token
 A program in Python contains a sequence of instructions.
 Python breaks each statement into a sequence of lexical components known as tokens.
Variables
A variable is “a name that is assigned to a value.”
 The assignment operator, = , is used to assign values to variables.
 An immutable value is a value that cannot be changed.
Eg: >>>num=10
>>> k=num
>>> print(k)
O/P : 10
In Python the same variable can be associated with values of different type during program
execution.
Eg : var = 12 integer var = 12.45
float
var = 'Hello' string
4 PROBLEM SOLVING USING PYTHON UNIT-I

Basic Input and Output


In Python, input is used to request and get information from the user, and print is used to display
information on the screen.
Variable Assignment and Keyboard Input
 The value can come from the user by use of the input function. Eg :
>>> name=input('what is your name : ')
O/P : what is your name : ABC
 All input is returned by the input function as a string type.
 For the input of numeric values, Python provides built-in type conversion functions int() and float().
Eg :
>>> age=int(input('Enter your age : ')) O/P : Enter
your age : 18
All input is returned by the input function as a string type. Built-in functions int() and float()
can be used to convert a string to a numeric type.
Chapter 2 : Data and Expression
2.1 Literals
 A literal is a sequence of one or more characters that stands for itself.
 Literals often referred to as constant values that have a fixed value. Python allows
several kinds of literals:
 Numeric Literals
 String Literals
Numeric Literals
 A numeric literal is a literal containing only the digits 0–9, a sign character (1 or 2) and a possible
decimal point.
 Commas are never used in numeric literals. There are 3
Numerical types
 integers : positive or negative whole numbers with no decimal points ( Eg : 2, -6, 3, 5 )
 Floating point : Consists of Fractional part. ( Eg. 1.4, 5.6 )
 Complex numbers ( Eg. 2+3j )
Limits of Range in floating point representation
 No limit to the size of an integer that can be represented in Python.
 Floating-point values, Python providing a range of 10 -308 to 10 +308 with 16 to 17 digits of
precision.
Limitations of floating point representation
 Arithmetic overflow problem :
 If you are trying to multiply two long floating point integers, we get the result as
inf ( infinity )
Eg : >>>1.5e200 * 2.0e210

5 PROBLEM SOLVING USING PYTHON UNIT-I

>>> inf
 Arithmetic underflow problem :
 This problem occurs in division.
 If denominator is larger than numerator, then it will result in zero.
Eg: 1/10000=0.00001
 Loss of precision problem :
 This problem occurs in division.
 If numerator divided by denominator, then if the result is never ending.
Eg : 10/3 = 3.33333

String literals in Python


 Single Quote  ‘ ‘
 Double Quote  “ “
 Triple Quote  ‘’’ ‘’’
 Represent the string either in ‘ PYTHON ’ or “ PYTHON “
 Triple Quote is used to represent “ multi line string “
Eg :
‘’’ WELCOME TO
PYTHON PROGRAMMING ‘’’
Number Formatting
The built-in format function can be used to produce a value containing a specific number of decimal places.
Syntax :
format(value, format_specifier)
where value is the value to be displayed
format_specifier can contain specific number of decimal places. Eg:
format(12/5, '.2f') -> '2.40'
format(5/7, '.2f') -> '0.71‘
format specifier '.2f' rounds the result to two decimal places.
String Formatting
 A built-in-function used to control how the strings are displayed.
Syntax :
format(value, format_specifier)
where value is the value to be displayed
format_specifier can contain a combination of formatting options.
 Formatting options can be left ( ‘<‘ ), right ( ‘ > ‘ ), center ( ‘ ^ ‘)
 Default formatting is LEFT justified
Example :
 To produce the string 'Hello' left-justified in a field width of 20 characters would be done as
follows :
format('Hello', ' < 20') ➝ 'Hello '
 To right-justify the string, the following would be used
format('Hello', ' > 20') ➝ ' Hello‘

6 PROBLEM SOLVING USING PYTHON UNIT-I

 To center the string the '^' character is used


format('Hello', '^20') ➝ ' Hello ‘
ESCAPE SEQUENCE IN PYTHON
 Control characters are nonprinting characters used to control the display of output.
 Represented by a combination of characters called an escape sequence .
 An escape sequence is a string of one or more characters used to denote control characters.
 To print the special characters in the screen, we use the escape sequence. The backslash
(\) serves as the escape character in Python.
EXAMPLE :
>>>print('Hello\nJennifer Smith') O/P:
Hello
Jennifer Smith
>>> print ('what\'s your name?') O/P : what's
your name?
>>> print ('what's your name?')
O/P : SyntaxError: invalid syntax
Implicit Line Joining
 Matching parentheses, square brackets, and curly braces can be used to span a logical program line
on more than one physical line.
Explicit Line Joining
 Program lines may be explicitly joined by use of the backslash (\).

Identifier
• An identifier is a sequence of one or more characters used to name a given program element.

7 PROBLEM SOLVING USING PYTHON UNIT-I

Rules for Framing Identifiers :


 Python is case sensitive.
Eg : username is not same as userNAME.
 Identifiers may contain letters and digits, but cannot begin with a digit.
 The underscore character, _, is also allowed but it should not be used as the first character.
 Spaces are not allowed as part of an identifier.
NAMING AN IDENTIFIER
Valid identifiers Invalid identifiers Reason invalid

totalSales ‘totalsales’ Quotes not allowed

totalsales Total sales Spaces not allowed


salesFor2020 2020sales Cannot begin with a digit

Sales_for_2020 _sales2020 Should not begin with an underscore

To check whether a given identifier is a keyword in python.


>>> 'exit' in dir( builtins ) O/P : True
>>> 'exit_program' in dir( builtins ) O/P : False
Keywords in python
 Python keywords are special reserved words that have specific meanings.
 Python 3.8, there are thirty-five keywords.
 A keyword is an identifier that has predefined meaning in a programming language.
 Cannot be used as a “regular” identifier.
Eg: >>> and=10
O/P : SyntaxError: invalid syntax

The keyword module in python provides two helpful members for dealing with keywords.

8 PROBLEM SOLVING USING PYTHON UNIT-I

Eg :
 kwlist provides a list of all the python keywords for the version which you are running.
 iskeyword() provides a way to determine if a string is also a keyword.

>>> import keyword


>>> keyword.kwlist
O/P : ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> len(keyword.kwlist) O/P : 35
Datatypes in python
Value :
 A Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
datatypes.)
Data type:
 Every value in Python has a data type.
 It is a set of values, and the allowable operations on those values. type() function
is used to determine the type of datatype.

NUMBERS
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Pythn supports integers, floating point numbers and complex numbers.
Integers Long Float Complex
They are often called as integers or int. They are positive or negative whole numbers with no decimal points.
They are long integers. They can also be represented in octal and hexa decimal representation
They are written with a decimal point dividing the integer and the fractional parts.
They are of the form a+bj
Where a and b are floats and j represents the square root of -
1(which is an imaginary number). Real part of the number is a, and the imaginary part is b.

9 PROBLEM SOLVING USING PYTHON UNIT-I

Eg : 65 Eg: 5692431L Eg : 56.778 Eg : 5+3j

Sequence
 A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable (values cannot be changed)
datatypes.
 There are three types of sequence data type available in Python, they are
1. Strings, 2. Lists, 3. Tuples
Strings
 A String in Python consists of a series or sequence of characters.
Single quotes(' ') E.g., 'This a string in single quotes' ,
Double quotes(" ") E.g., "'This a string in double quotes'" ,
Triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple lines and
sentences."""
 Individual character in a string is accessed using a subscript(index).
 Strings are Immutable i.e the contents of the string cannot be changed after it is created.

Lists
 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 datatypes.
Eg : lt = [ 10, -20, 15.5, ‘ABC’, “XYZ” ]
Tuples
 In tuple the set of elements is enclosed in parentheses ( ).
 A tuple is an immutable list.
 Once a tuple has been created, you can't add elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
 Tuples are faster than lists.
 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.
 Altering the tuple data type leads to error.
Eg : tpl = ( 10, -20, 15.5, ‘ABC’, “XYZ” )
Dictionaries
 A dictionary maps keys to values.
10 PROBLEM SOLVING USING PYTHON UNIT-I

 Lists are ordered sets of objects, whereas dictionaries are unordered sets.
 Dictionary is created by using curly brackets. i,e.{ }
 Dictionaries are accessed via keys and not via their position.
 The values of a dictionary can be any Python data type. So dictionaries are unordered key-value
pairs(The association of a key and a value is called a key- value pair)
Eg : Creating a dictionary:
>>> food = {"ham":"yes", "egg" : "yes", "rate":450 }
Set :
 Python also provides two set types, set and frozenset.
 The set type is mutable, while frozenset is immutable.
 They are unordered collections of immutable objects.
Boolean :
 The boolean data type is either True or False.
 In Python, boolean variables are defined by the True and False keywords.
 The keywords True and False must have an Upper Case first letter.

OPERATORS IN PYTHON
 An operator is a symbol that represents an operation that may be performed on one or more
operands.
 Operators that take one operand are called unary operators.
 Operators that take two operands are called binary operators.
 20 - 5 ➝ 15 ( - as binary operator)
 - 10 * 2 ➝ -20 ( - as unary operator)
Types of operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operator
 Bitwise Operator
 Identity Operator
 Membership Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication,
etc.

Operator Meaning Example

+ Add two operands or unary plus x + y+ 2

- Subtract right operand from the left or unary minus x - y- 2


11 PROBLEM SOLVING USING PYTHON UNIT-I

* Multiply two operands x*y

Divide left operand by the right one (always results into x/y
/
float)

Modulus - remainder of the division of left operand by the right


%
x % y (remainder of x/y)
Floor division - division that results into whole number x // y
//
adjusted to the left in the number line

x**y (x to the
** Exponent - left operand raised to the power of right power y)

and
Relational Operators
• Relational operators are used to compare values. It returns either True or False according to
the condition.

Operator Meaning Example

Greater than - True if left operand is greater x>y


>
than the right

Less than - True if left operand is less than the x<y


<
right

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand


>= x >= y
is greater than or equal to the right

Less than or equal to - True if left operand is x <= y


<=
less than or equal to the right

Logical operators
• Logical operators are the and, or, not operators.

12 PROBLEM SOLVING USING PYTHON UNIT-I

Operator Meaning Example

True if both the operands


x and y
are true

True if either of the x or y


operands is true
not True if operand is false (complements the operand)
not x
Eg:

x = True y = False
print('x and y is',x and y) print('x or y
is',x or y) print('not x is',not x)

Assignment Operator
• Assignment operators are used to assign the values to variables.

Operator Example Equivalent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

BITWISE OPERATORS
• Bitwise operators are working with individual bits of data.

13 PROBLEM SOLVING USING PYTHON UNIT-I

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)


For example, 2 is 10 in binary and 7 is 111.
In the table : Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Identity operators
Identity operators : is and is not are used to check the memory locations of two objects.
 is and is not are the identity operators in Python.
 They are used to check if two values (or variables) are located on the same part of the memory.
 For list, if two variables that are equal does not imply that they are identical. It is because
the interpreter locates them separately in memory although they are equal.
Operator Meaning Example

True if the operands are identical (refer to x is True


is
the same object)

True if the operands are not identical (do x is not True


is not
not refer to the same object)

Example :
0x1=5; y1=5 x2=‘Hello’;y2=‘Hello’ x3=[1,2,3]; y3=[1,2,3]
print(x1 is not y1) print(x2 is y2) print(x3 is y3)
14 PROBLEM SOLVING USING PYTHON UNIT-I

Membership operators
Membership operators : in and not in for determining the presence of items in a sequence such as
strings, lists and tuples.
 in and not in are the membership operators in Python.
 They are used to test whether a value or variable is found in a sequence(string, list, tuple, set
and dictionary)

Operator Meaning Example


in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence
5 in x

5 not in x
 In dictionary, we can only test for the presence of key not the value.

Example :

x= “Hello World”
y={1:’a’,2:’b’}
print(‘H’ in x) print(‘Hello’ not in x) print(1 in y)
print(‘a’ in y)
What Is an Expression?
 An expression is a combination of symbols or single symbol that evaluates to a value.
 A subexpression is any expression that is part of a larger expression.
 Expressions, most commonly, consist of a combination of operators and operands, Eg : 4
+ (3 * k)
Operator precedence
 Precedence : Defines the priority of an operator.
Associativity :
 When an expression contains operators with equal precedence then the associativity property
decides which operation is to be performed first.
 Associativity implies the direction of execution and is of two types,left to right and right to
left.

15 PROBLEM SOLVING USING PYTHON

What Is a Control Structure?

A control statement is a statement that determines the control flow of a set of instructions. A control
structure is a set of instructions and the control statements controlling their execution. Three fundamental
forms of control in programming are sequential, selection, and iterative control.
• Sequential control is an implicit form of control in which instructions are executed in the order that
they are written.
• Selection control is provided by a control statement that selectively executes
instructions.
• iterative control is provided by an iterative control statement that repeatedly executes instructions.
Indentation in Python
• A header in Python is a specific keyword followed by a colon.
• The set of statements following a header in Python is called a suite(commonly called a block).
• A header and its associated suite are together referred to as a clause.
Selection Control or Decision Making statement
A selection control statement is a control statement providing selective execution of instructions.
• if statements
• if-else statements
• Nested if statements
• Multi-way if-elif-else statements
if statement:
• An if statement is a selection control statement based on the value of a given Boolean expression.
• The if statement executes a statement if a condition is true.

1 PROBLEM SOLVING USING PYTHON

Details of the if Statement


Points to Remember
• A colon (:) must always be followed by the condition.
• The statement(s) must be indented at least one space right of the if statement.
• In case there is more than one statement after the if condition, then each statement must be
indented using the same number of spaces to avoid indentation errors.
• The statement(s) within the if block are executed if the boolean expression evaluates to true.
Flow Chart for if statement
Example :

num1=eval(input(“Enter First Number: “))


num2=eval(input(“Enter Second Number: “)) if num1-
num2==0:
print(“Both the numbers entered are Equal”)
Output :
Enter First Number: 12
Enter Second Number: 12
Both the numbers entered are Equal

2 PROBLEM SOLVING USING PYTHON

if-else statements
• The if-else statement takes care of a true as well a false condition.

Flow Chart for if-else statement

Example :
num1=eval(input("enter first number"))
num2=eval(input("enter second number")) if
num1>num2:
print(num1,"is greater than ", num2)
else:
print(num2,"is greater than ", num1)
Output :
enter first number 12 enter second
number 45
45 is greater than 12

Nested if statements
• One if statement inside another if statement then it is called a nested if statement.
Syntax :
if Boolean-expression1:
if Boolean-expression2:
statement1 else:
else:
statement2

statement3

3 PROBLEM SOLVING USING PYTHON

Flow chart

Example :

num=eval(input(“Enter the number :”))


if num>=0:
if num==0:
print(“Entered number “, num, “ is Zero”)
else:
print(“Entered number “, num, “ is positive”) else:
print(“Entered number “, num, “ is negative”) if...elif...else statement

• Boolean expressions are checked from top to bottom.


• When a true condition is found, the statement associated with it is executed and the rest of the
conditional statements are skipped.
• If none of the conditions are found true then the last else statement is executed.
• If all other conditions are false and if the final else statement is not present then no action takes
place.
Syntax of if...elif...else

if test expression: Body of if


elif test expression: Body of elif else:
Body of else Flow Chart:

4 PROBLEM SOLVING USING PYTHON

Example:

day=int(input(“Enter the day of week:”))


if day==1:
print(“ Its Monday”)
elif day==2: print(“Its Tuesday”)
elif day==3:
print(“Its Wednesday”)
elif day==4:
print(“Its Thursday”)
elif day==5: print(“Its Friday”)
elif day==6:
print(“Its Saturday”)
elif day==7:
print(“ Its Sunday”)
else:
print(“Sorry!!! Week contains only 7 days”)
Conditional expressions
Syntax :

Example :
Expression1 if condition else
Expression2 num1=8; num2=9
print(num1) if num1<num2 else print(num2)

Example:
To check whether the given year is leap year or not

year=int(input(“enter the year”))


if(((year%4==0)and(year%100!=0))or(year%400==0)):
print(year,”is a leap year”)
else:
print(year,”is not a leap year”)
Boolean Expressions

The Boolean data type contains two Boolean values, denoted as True and False in Python. A Boolean
expression is an expression that evaluates to a Boolean value.
Iteration statements

• Iteration statements or loop statements allow us to execute a block of statements as long as the
condition is true.
• An iterative control statement is a control statement that allows for the repeated execution of
a set of statements.
Type Of Iteration Statements

• While Loop
• For Loop

5 PROBLEM SOLVING USING PYTHON

while Statement

A while statement is an iterative control statement that repeatedly executes a set of statements based on a
provided Boolean expression ( condition ).
Syntax :

while condition:
suite (or) statements

Details of while statement

• The reserved keyword while begins with the while statement.


• The test condition is a Boolean expression.
• The colon (:) must follow the test condition, i.e. the while statement be terminated with a
colon (:).
• The statement(s) within the while loop will be executed till the condition is true, i.e. the condition is
evaluated and if the condition is true then the body of the loop is executed.
• When the condition is false, the execution will be completed out of the loop or in other
words, the control goes out of the loop.
FLOW CHART
Example :

x=1
while x < 3:
print(x)
x=x+1

OUTPUT :

6 PROBLEM SOLVING USING PYTHON

Execution

Python Looping Techniques

• An infinite loop is an iterative control structure that never terminates (or eventually terminates with a
system error).
Example :

while True:
num = int(input("Enter an integer: ")) print("The
double of",num,"is",2 * num) Definite vs. Indefinite
Loops
• A definite loop is a program loop in which the number of times the loop will iterate can be
determined before the loop is executed.
• A indefinite loop is a program loop in which the number of times the loop will iterate is not known
before the loop is executed.
Input Error Checking

• The while statement is well suited for input error checking.

Example :

a=5;b=3
ch=int(input("Enter the choice"))
while ch!=1 and ch!=2:
ch=int(input("Enter either 1 or 2"))
if ch==1:
print(a+b)
else:
print(a-b)

7 PROBLEM SOLVING USING PYTHON

range() function

Example of range() function Output

range(5) [0,1,2,3,4]
range(1,5) [1,2,3,4]

range(1,10,2) [1,3,5,7,9]

range(5,0,-1) [5, 4, 3, 2, 1]

range (-4,4) [-4, -3, -2, -1, 0, 1, 2, 3]

range (-4,4,2) [-4, -2, 0, 2]

range(0,1) [0]

range(1,1) Empty

range(0) Empty

for loop
• A for statement is an iterative control statement that iterates once for each element in a specified
sequence of elements.
• Used to construct definite loops.

8 PROBLEM SOLVING USING PYTHON

Syntax :
for var in sequence:
statement(s)
………………………………
……………………………
………………………………
• for and in are essential keywords to iterate the sequence of values.
• var takes on each consecutive value in the sequence
• statements in the body of the loop are executed once for each value
Flow chart
Example: for loop

• The for loop repeats a group of statements for a specified number of times. for var in
range(m,n):
print var
• function range(m, n) returns the sequence of integers starting from m, m+1, m+2,
m+3…………… n-1.
Example :
for i in range(1,6):
print(i)
Lists
A list is a linear data structure, thus its elements have a linear ordering.

 A list in Python is a mutable linear data structure, denoted by a comma-separated list of elements
within square brackets, allowing mixed-type elements.

Example :

• lst = [1,2,3,4,5]
• lst = [‘a,’b’,’c’,’d’]
• lst= [1,’ABC’,98.5,’HELLO’]
➢ Operations commonly performed on lists include retrieve, update, insert, remove, and
append.
➢ A list traversal is a means of accessing, one-by-one, the elements of a list.

9 PROBLEM SOLVING USING PYTHON

Python List Type

A list in Python is a mutable, linear data structure of variable length, allowing mixed-type elements.
Mutable means that the contents of the list may be altered. Lists in Python use zerobased indexing.

All lists have index values 0 ... n-1, where n is the number of elements in the list. Lists are denoted by a
comma-separated list of elements within square brackets

[1, 2, 3] ['one', 'two', 'three'] ['apples', 50, True]

An empty list is denoted by an empty pair of square brackets, [].

lst = [10,20,30,40,50]

lst[0]=10 lst[1]=20

lst[2]=30 lst[3]=40

lst[4]=50

 Negative index : Right to Left lst[-1]=50

lst[-2]=40 lst[-3]=30

lst[-4]=20 lst[-5]=10

 Append ➔ Add elements at the end of the list. Syntax :

lst.append(element)

Eg : lst.append(60)

 Update ➔ Changing the elements in the list. Eg : lst[2]=25


 Remove ➔ Delete element in the list.

Eg : del lst[3]

10 PROBLEM SOLVING USING PYTHON

Slicing ➔ Creating Sub-List lst[1:3]=[20,30]

lst[1:4]=[20,30,40] lst[:4]=[10,20,30,40]

lst[2:]=[30,40,50]

Built-in-function

Return value but not change the list.

 listname.count(element)

 listname.index(element)

 listname.index(element,start)

Doesn’t Return value but change the list.

 listname.append(element)

 listname.extend(list)

 listname.pop(index)

 listname.insert(index,element)

 listname.remove(element)

 listname.reverse() Listname.sort()

Assigning & Copying list

>>> lst1=[1,2,3,4]

>>> lst2=lst1

>>> print(lst2) [1, 2, 3, 4]

List Comprehension

List comprehensions in Python provide a concise means of generating a more varied set of sequences than
those that can be generated by the range function.

 List of elements with squares.

11 PROBLEM SOLVING USING PYTHON


Syntax :

lst= [ expression for variable in range ]

Eg:

lst = [ i**2 for i in range(1,6)]

print(lst)

Example: lst1=[1,2,3,4]

lst2=[2,5,6,7]

pair=[(x,y)for x in lst1 for y in lst2 if x!=y]

print(pair)

Looping in List

lst = [10,20,30,40,50]

for i in lst:

print(i) O/P :

10

20

30

40

50

Operation Fruit= [‘banana’, ’apple’, ’cherry’]

Replace Fruit[2]=‘coconut’ [‘banana’, ’apple’, ’coconut’]

12 PROBLEM SOLVING USING PYTHON

Delete Del fruit[1] [‘banana’, ’cherry’]


Insert Fruit.insert(2,’pear’) [‘banana’, ’apple’, ‘pear’,
‘cherry’]

Append Fruit.append(‘peach’) [‘banana’, ’apple’, ’cherry’,


’peach’]

Sort Fruit.sort() [‘apple’, ‘banana’, ‘cherry’]

Reverse Fruit.reverse() [‘cherry’, ‘banana’, ‘apple’]

Nested Lists

lst = [[1, 2 ,3], [4, 5, 6], [7, 8, 9]]

Tuples

 A tuple is an immutable linear data structure denoted by parentheses(optional) which cannot be


altered.

tup=() tup1=(“apple”,”banana”,1997,2020)

tup2=(1,2,3,4,5)

tup3=“a”, ”b”, ”c”, ”d”

Basic Operations

a=(10,20,20,40,50,60,10,80) b=(1,2,3,4,5,6)

 Length : len(a) : 8

 Concatentation : a+b : (10, 20, 20, 40, 50, 60, 10, 80, 1, 2, 3, 4, 5, 6)

13 PROBLEM SOLVING USING PYTHON

 Repetition : a*2 : (10, 20, 20, 40, 50, 60, 10, 80, 10, 20, 20, 40, 50, 60, 10, 80)

 Membership : 20 in a : True

 Maximum/Minimum : max(b) : 6 ; min(a) : 10

 Index : a.index(40) : 3
 Count : a.count(20) : 2

 Conversion to Tuple

Converting List to Tuple using tuple() function

lst=[]

for i in range(5):

#ele=int(input())

lst.append(i) print(lst)

tup=tuple(lst) print(tup)

Sample program for tuple : Counting No.of ODD & EVEN numbers in tuple

input_tuple=() final_tuple=()

oddc=0 evenc=0

for i in range(1,11): input_tuple=(i)

final_tuple=final_tuple+(input_tuple,)

print(final_tuple)

for x in final_tuple:

temp=int(x)

if temp%2==0:

evenc=evenc+1

14 PROBLEM SOLVING USING PYTHON

else:

oddc=oddc+1

print("Count of even numbers : ",evenc)

print("Count of Odd numbers : ",oddc)


15 FUNCTIONS – UNIT III NOTES

Program Routines:
A program routine is a named group of instructions that accomplishes some task. A routine
may be invoked (called) as many times as needed in a given program. A function is Python’s version of a
program routine.
What is a Function routine?
• A routine is a named group of instructions performing some task.
• A routine can be invoked ( called ) as many times as needed in a given program
• A function is Python’s version of a program routine.
Advantages of Function:
• Helpful debugging your code.
• Reusability of code.
• Easier to understand.
• Easier to maintain.
Function definition:
• Every function should start with ‘def’ keyword.
• Every function should have name( not equal to any keyword)
• Parameters / Arguments (optional) included in b/w parenthesis.(formal)
• Every function name with/without arguments should end with(:)
• return  empty / value
• Multi value return can be done ( tuples )
• Every function must be defined before it is called.
Syntax:
def function_name(arg1, arg2, …. arg n) :
program statement 1 program
statement 2
--------
-------- return Function call:
• Function name
• Arguments / Parameters(actual)
Actual arguments & Formal parameters:
Equal to the function definition • Actual arguments, or simply “arguments,” are the values
passed to functions to be operated on. • Formal parameters, arguments passed.
Value-returning functions:
or simply “parameters,” are the “placeholder” names for the • A value-returning function in
Python is a program routine called for its return value, and is therefore similar to a mathematical
function.
Non-value-returning functions:
• A non-value-returning function is a function called for its side effects, and not for a returned function
value.
The local and global scope of a variable:
• Variables and parameters that are initialised within a function including parameters, are said to exist
in that function’s local scope. Variables that exist in local scope are called local variables.
• Variables that are assigned outside functions are said to exist in global scope.
Therefore, variables that exist in global scope are called global variables.

You might also like