Python Notes
Python Notes
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
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
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 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.
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.
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:
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.
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:
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.
>>> 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
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: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Syntax for input() is:
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
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.
TUPLE ASSIGNMENT
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:
(a, b) = (b, a)
-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'
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
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
!= 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)
Operator Description
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
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.
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
>>>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
Example:
def my_add(a,b):
c=a+b
return c
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:
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.
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)
2
.random-Generate pseudo-random numbers
random.randrange(stop) random.randrange(start, stop[, step])
random.uniform(a, b)
-Return a random floating point number
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:
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
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.
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
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
w we
e
l lom
e
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
Fruitful function
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion
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)
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.
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)
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)
sum=sum(n)
print("Fact is",sum)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
panimalarpanimalar
panimalar
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
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
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
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list Output into
array
a=[2,3,4,5]
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
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
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)
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)
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:
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
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)
>>>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
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.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
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
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.
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.
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:
>>>
>>> 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
in raise
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
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.
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.
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.
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!"
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’}
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
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
>>> 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.
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.
The output
10 15 20 25
10,15,20,25
10 15 20 25
10:15:20:25
10-----15-----20-----25
"10.2e" Format the float item in scientific notation with width 10 and precision
2.
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
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
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.
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)
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
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:
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
>>>
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)
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:
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))
Typecode Details
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.
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')
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']
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.
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
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.
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.
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:
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
"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.
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.
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
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
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.
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.
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
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
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).
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 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
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
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
>>> 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
Identifier
• An identifier is a sequence of one or more characters used to name a given program element.
The keyword module in python provides two helpful members for dealing with keywords.
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.
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.
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.
Divide left operand by the right one (always results into x/y
/
float)
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.
Logical operators
• Logical operators are the and, or, not operators.
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.
= 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.
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)
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.
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.
if-else statements
• The if-else statement takes care of a true as well a false condition.
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
Flow chart
Example :
Example:
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
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
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
x=1
while x < 3:
print(x)
x=x+1
OUTPUT :
Execution
• 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
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)
range() function
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(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.
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.
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
lst = [10,20,30,40,50]
lst[0]=10 lst[1]=20
lst[2]=30 lst[3]=40
lst[4]=50
lst[-2]=40 lst[-3]=30
lst[-4]=20 lst[-5]=10
lst.append(element)
Eg : lst.append(60)
Eg : del lst[3]
lst[1:4]=[20,30,40] lst[:4]=[10,20,30,40]
lst[2:]=[30,40,50]
Built-in-function
listname.count(element)
listname.index(element)
listname.index(element,start)
listname.append(element)
listname.extend(list)
listname.pop(index)
listname.insert(index,element)
listname.remove(element)
listname.reverse() Listname.sort()
>>> lst1=[1,2,3,4]
>>> lst2=lst1
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.
Eg:
print(lst)
Example: lst1=[1,2,3,4]
lst2=[2,5,6,7]
print(pair)
Looping in List
lst = [10,20,30,40,50]
for i in lst:
print(i) O/P :
10
20
30
40
50
Nested Lists
Tuples
tup=() tup1=(“apple”,”banana”,1997,2020)
tup2=(1,2,3,4,5)
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)
Repetition : a*2 : (10, 20, 20, 40, 50, 60, 10, 80, 10, 20, 20, 40, 50, 60, 10, 80)
Membership : 20 in a : True
Index : a.index(40) : 3
Count : a.count(20) : 2
Conversion to Tuple
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
final_tuple=final_tuple+(input_tuple,)
print(final_tuple)
for x in final_tuple:
temp=int(x)
if temp%2==0:
evenc=evenc+1
else:
oddc=oddc+1
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.