0% found this document useful (0 votes)
49 views128 pages

11th IP Unit-2 Introduction To Python

Uploaded by

f0911157
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
49 views128 pages

11th IP Unit-2 Introduction To Python

Uploaded by

f0911157
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 128

CLASS-11

SUBJECT - INFORMATICS PRACTICES (065)

UNIT : 2
Introduction To Python
www.ipzone.wordpress.com
PART - 1
Getting Started with Python

www.ipzone.wordpress.com
Python Introduction

It is widely used general purpose,high level programming


language.Developed by Guido van Rossum in 1991.
It is used for:
software development,
web development (server-side),
system scripting,
Mathematics.

www.ipzone.wordpress.com
Features of Python

1. Easy to use – Due to simple syntax rule


2. Interpreted language – Code execution &
interpretation line by line
3. Cross-platform language – It can run on
windows,linux,macinetosh etc. equally
4. Expressive language – Less code to be written as it
itself express the purpose of the code.
5. Completeness – Support wide rage of library
6. Free & Open Source – Can be downloaded freely
and source code can be modify for improvement

www.ipzone.wordpress.com
Shortcomings of Python

1. Lesser libraries – as compared to other


programming languages like c++,java,.net
2. Slow language – as it is interpreted languages,it
executes the program slowly.
3. Weak on Type-binding – It not pin point on use of a
single variable for different data type.

www.ipzone.wordpress.com
Installing Python

Two Steps Only –

1. Download Python distribution


2. Python installation process

www.ipzone.wordpress.com
Installing Python

1. Download Python distribution


You can download python distribution from the link given below
https://www.python.org/downloads/

Note – Download only that python distribution/MSI Installer, which is best suited for
the Operating system on which you want to install it.

www.ipzone.wordpress.com
Installing Python

2. Python installation process


1. Double-click the icon labeling the file <version>.exe
Popup window will appear

Click on Run option


www.ipzone.wordpress.com
Installing Python

2. Setup popup window will appear

If the Python Installer finds an earlier version of Python installed on your computer,
the Install Now message will instead appear as Upgrade Now(and the checkboxes will
not appear).
Highlight the IVnistital:lpNyotwho(no.rmUypkgvsra.idwww.ipzone.wordpress.com
nefoNrorweg)umlaersusapgdea,taensd then click it
Installing Python

3. User Account Conrol pop-up window will appear

Click the Yes button.

www.ipzone.wordpress.com
Installing Python

4. A new Python <version> Setup pop-up window will appear


with a Setup Progress message and a progress bar.

www.ipzone.wordpress.com
Installing Python

5. Soon, a new Python <version> Setup pop-up window will


appear with a Setup was successfully message

Click the close button


www.ipzone.wordpress.com
How to work in Python

After installation of python ,we can work on it in following ways

(i) in Interactive mode


(ii) in Script mode

www.ipzone.wordpress.com
How to work in Python

(i) in Interactive mode


* Search the python.exe file in the drive in which it is
installed.
If found double click it to start python in interactive
mode

www.ipzone.wordpress.com
How to work in Python

* Click start button -> All programs ->


python<version>->IDLE(Python GUI)

www.ipzone.wordpress.com
How to work in Python
Python command
prompt >>>

Type the following at prompt


print “hello”
print 8*3
print 3**3
k=3+4*3
print k

www.ipzone.wordpress.com
How to work in Python

(ii) in Script mode


Step 1 (Create program file)
Below steps are for simple hello world program
a. Click Start button->All Programs ->
Python<version>->IDLE
b.Now click File->New in IDLE Python Shell
Now type
print “hello”
print “world”
print “python is”,”object oriented programming lang.”
c.Click File->Save and then save the file with filename
and .py extension
www.ipzone.wordpress.com
How to work in Python

(ii) in Script mode


Step 2 (Run program file)
a. Click Open command from IDLE’s File menu and select the file
you have already saved
b. Click Run-> Run Module
c. It will execute all the commands of program file and display
output in separate python shell window
Note :- Python comes in 2 flavours – python 2.x and python 3.x .
Later one is Backward incompatible language as decide by Python
Software foundation(PSF). Mean code written in 2.x will not execute
on 3.x . Visit the below link for difference between 2.x & 3.x
https://www.geeksforgeeks.org/important-differences-
between-python-2-x-and-python-3-x-with-examples/
www.ipzone.wordpress.com
PART - 2
Basics of Python
Programming

www.ipzone.wordpress.com
Python basics

Python 3.0 was released in 2008. Although this version is supposed


to be backward incompatibles, later on many of its important
features have been back ported to be compatible with version 2.7
Python Character Set
A set of valid characters recognized by python. Python uses the traditional ASCII
character set. The latest version recognizes the Unicode character set. The ASCII
character set is a subset of the Unicode character set.
Letters :– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbol available over keyboard
White spaces:– blank space,tab,carriage return,new line, form feed
Other characters:- Unicode

www.ipzone.wordpress.com
Input and Output

var1=‘Computer Science'
var2=‘Informatics Practices'
print(var1,' and ',var2,' )
Output :-
Computer Science and Informatics Practices
raw_input() Function In Python allows a user to give input to a program from a
keyboard but in the form of string.
NOTE : raw_input() function is deprecated in python 3
e.g.
age = int(raw_input(‘enter your age’))
percentage = float(raw_input(‘enter percentage’))
input() Function In Python allows a user to give input to a program from a keyboard
but returns the value accordingly.
e.g.
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
NOTE : input() function always enter string value in python 3.so on need int(),float()
function can be used for data conversion.
www.ipzone.wordpress.com
Indentation
Indentation refers to the spaces applied at the beginning of
a code line. In other programming languages the
indentation in code is for readability only, where as the
indentation in Python is very important.
Python uses indentation to indicate a block of code or used
in block of codes.
E.g.1
if 3 > 2:
print(“Three is greater than two!") //syntax error due to not indented

E.g.2
if 3 > 2:
print(“Three is greater than two!") //indented so no error
www.ipzone.wordpress.com
Token

Smallest individual unit in a program is known as token.


1. Keywords
2. Identifiers
3. Literals
4. Operators
5. punctuators

www.ipzone.wordpress.com
Keywords

Reserve word of the compiler/interpreter which can’t be


used as identifier. and exec not

as finally or

assert for pass

break from print

class global raise

continue if return

def import try

del in while

elif is with

else lambda yield

except

www.ipzone.wordpress.com
Identifiers

A Python identifier is a name used to identify a variable,


function, class, module or other object.
*An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
* Python does not allow special characters
* Identifier must not be a keyword of Python.
*Python is a case sensitive programming language.
Thus, Rollnumber and rollnumber are two different
identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no
Some invaVliisdit:idpyethnont.imfiyekvrs.:in2fowww.ipzone.wordpress.com
rrnreog,ublarreupadka,tems y.book,data-cs
Identifiers-continue

Some additional naming conventions


1. Class names start with an uppercase letter. All other
identifiers start with a lowercase letter.
2. Starting an identifier with a single leading underscore
indicates that the identifier is private.
3. Starting an identifier with two leading underscores
indicates a strong private identifier.
4. If the identifier also ends with two trailing
underscores, the identifier is a language-defined
special name.

www.ipzone.wordpress.com
Literals

Literals in Python can be defined as number, text, or other


data that represent values to be stored in variables.

Example of String Literals in Python


name = ‘Johni’ , fname =“johny”
Example of Integer Literals in Python(numeric literal)
age = 22
Example of Float Literals in Python(numeric literal)
height = 6.2
Example of Special Literals in Python
name = None
www.ipzone.wordpress.com
Literals
Escape sequence/Back slash character constants
Escape Sequence Description
\\ Backslash (\)

\' Single quote (')

\" Double quote (")

\a ASCII Bell (BEL)

\b ASCII Backspace (BS)

\f ASCII Formfeed (FF)

\n ASCII Linefeed (LF)

\r ASCII Carriage Return (CR)

\t ASCII Horizontal Tab (TAB)

\v ASCII Vertical Tab (VT)

\ooo Character with octal value ooo

\xhh Character with hex value hh

www.ipzone.wordpress.com
Operators

Operators can be defined as symbols that are used to


perform operations on operands.

Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

www.ipzone.wordpress.com
Operators continue

1. Arithmetic Operators
Arithmetic Operators are used to perform arithmetic
operations like addition, multiplication, division etc.
Operators Description Example

+ perform addition of two number x=a+b

- perform subtraction of two number x=a-b

/ perform division of two number x=a/b

* perform multiplication of two number x=a*b

% Modulus = returns remainder x=a%b

Floor Division = remove digits after the decimal


// x=a//b
point

** Exponent = perform raise to power x=a**b

www.ipzone.wordpress.com
Operator continue

Arithmatic operator continue


e.g.
x=5
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

OUTPUT
('x + y =', 9) • Write a program in python to calculate the simple
('x - y =', 1) interest based on entered amount ,rate and time
('x * y =', 20)
('x / y =', 1)
('x // y =', 1)
('x ** y =', 625)

www.ipzone.wordpress.com
Operator continue
Arithmatic operator continue

# EMI Calculator program in Python

def emi_calculator(p, r, t):


r = r / (12 * 100) # one month interest
t = t * 12 # one month period
emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1)
return emi

# driver code
principal = 10000;
rate = 10;
time = 2;
emi = emi_calculator(principal, rate, time);
print("Monthly EMI is= ", emi)
www.ipzone.wordpress.com
Operator continue
Arithmatic operator continue
How to calculate GST
GST ( Goods and Services Tax ) which is included in netprice of
product for get GST % first need to calculate GST Amount by subtract original
cost from Netprice and then apply
GST % formula = (GST_Amount*100) / original_cost

# Python3 Program to compute GST from original and net prices.


def Calculate_GST(org_cost, N_price):
# return value after calculate GST%
return (((N_price - org_cost) * 100) / org_cost);

# Driver program to test above functions


org_cost = 100
N_price = 120
print("GST = ",end='')
print(round(Calculate_GST(org_cost, N_price)),end='')
print("%")
* Write a Python program to calculate the standard deviation

www.ipzone.wordpress.com
Operators continue

2. Relational Operators/Comparison Operator


Relational Operators are used to compare the values.
Operators Description Example

== Equal to, return true if a equals to b a == b

Not equal, return true if a is not equals


!= a != b
to b

Greater than, return true if a is greater


> a>b
than b

Greater than or equal to , return true if a


>= a >= b
is greater than b or a is equals to b

< Less than, return true if a is less than b a<b


Less than or equal to , return true if a is
<= a <= b
less than b or a is equals to b

www.ipzone.wordpress.com
Operator continue
Comparison operators continue
e.g.
x = 101
y = 121
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

Output
('x > y is', False)
('x < y is', True)
('x == y is', False)
('x != y is', True)
('x >= y is', False)
('x <= y is', True)
www.ipzone.wordpress.com
Operators continue
3. Assignment Operators
Used to assign values to the variables.
Operators Description Example

= Assigns values from right side operands to left side operand a=b

+= Add 2 numbers and assigns the result to left operand. a+=b

/= Divides 2 numbers and assigns the result to left operand. a/=b

*= Multiply 2 numbers and assigns the result to left operand. A*=b

-= Subtracts 2 numbers and assigns the result to left operand. A-=b

%= modulus 2 numbers and assigns the result to left operand. a%=b

//= Perform floor division on 2 numbers and assigns the result to left operand. a//=b

**= calculate power on operators and assigns the result to left operand. a**=b

www.ipzone.wordpress.com
Operators continue
4. Logical Operators
Logical Operators are used to perform logical operations on
the given two variables or values.
Operators Description Example
and return true if both condition are true x and y
return true if either or both
or x or y
condition are true

not reverse the condition not(a>b)


a=30
b=20
if(a==30 and b==20):
print('hello')

Output :-
hello
www.ipzone.wordpress.com
Operators continue
6. Membership Operators
The membership operators in Python are used to validate
whether a value is found within a sequence such as such as
strings, lists, or tuples.
Operators Description Example
in return true if value exists in the sequence, else false. a in list
not in return true if value does not exists in the sequence, else false. a not in list
E.g.
a = 22
list = [22,99,27,31]
In_Ans = a in list
NotIn_Ans = a not in list
print(In_Ans)
print(NotIn_Ans)
Output :-
True
False
www.ipzone.wordpress.com
Operators continue
7. Identity Operators
Identity operators in Python compare the memory locations of two
objects. Operators Description Example

is returns true if two variables point the same object, elsefalse a is b

e.g. is not returns true if two variables point the different object, elsefalse a is not b
a = 34
b=34
if (a is b):
print('both a and b has same identity')
else:
print('a and b has different identity')
b=99
if (a is b):
print('both a and b has same identity')
else:
print('a and b has different identity')
Output :-
both a and b has same identity
a and b has different identity

www.ipzone.wordpress.com
Operator continue
Operators Precedence :
highest precedence to lowest precedence table. Precedence is used to decide ,which operator
to be taken first for evaluation when two or more operators comes in an expression.

Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus,minus(method names for the last two are+@and -@)
* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction


>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
www.ipzone.wordpress.com
Punctuators

Used to implement the grammatical and structure of a


Syntax.Following are the python punctuators.

www.ipzone.wordpress.com
Barebone of a python program

#function definition comment


def keyArgFunc(empname, emprole):
print ("Emp Name: ", empname) Function
print ("Emp Role: ", emprole) indentation
return;
A = 20 expression
print("Calling in proper sequence")
keyArgFunc(empname = "Nick",emprole = "Manager" )
print("Calling in opposite sequence") statements
keyArgFunc(emprole = "Manager",empname = "Nick")

A python program contain the following components


a. Expression
b. Statement
c. Comments
d. Function
e. Block &n indentation
www.ipzone.wordpress.com
Barebone of a python program
a. Expression : - which is evaluated and produce result. E.g. (20 + 4) / 4
b. Statement :- instruction that does something.
e.g
a = 20
print("Calling in proper sequence")
c. Comments : which is readable for programmer but ignored by python
interpreter
i. Single line comment: Which begins with # sign.
ii. Multi line comment (docstring): either write multiple line beginning with # sign
or use triple quoted multiple line. E.g.
‘’’this is my
first
python multiline comment
‘’’
d. Function
a code that has some name and it can be reused.e.g. keyArgFunc in above
program
d. Block & indentation : group of statements is block.indentation at same level
create a block.e.g. all 3 statement of keyArgFunc function
www.ipzone.wordpress.com
Variables

Variable is a name given to a memory location. A variable can


consider as a container which holds value. Python is a type infer
language that means you don't need to specify the datatype of
variable.Python automatically get variable datatype depending
upon the value assigned to the variable.
Assigning Values To Variable
name = ‘python' # String Data Type
sum = None # a variable without value
a = 23 # Integer
b = 6.2 # Float
sum = a + b
print (sum)
Multiple Assignment: assign a single value to many variables
a = b = c = 1 # single value to multiple variable
a,b = 1,2 # multiple value to multiple variable
a,b = b,a # value of a and b is swaped

www.ipzone.wordpress.com
Variables
Variable Scope And Lifetime in Python Program
1. Local Variable
def fun():
x=8
print(x)

fun()
print(x) #error will be shown
2.Global Variable
x=8
def fun():
print(x) # Calling variable ‘x’ inside fun()

fun()
print(x) # Calling variable ‘x’ outside fun()

www.ipzone.wordpress.com
Dynamic typing

Data type of a variable depend/change upon the value


assigned to a variable on each next statement.
X = 25 # integer type
X = “python” # x variable data type change to string on just
next line
Now programmer should be aware that not to write like this:
Y = X / 5 # error !! String cannot be devided

www.ipzone.wordpress.com
Constants
A constant is a type of variable whose value cannot be changed. It is
helpful to think of constants as containers that hold information which
cannot be changed later.
In Python, constants are usually declared and assigned in a module. Here,
the module is a new file containing variables, functions, etc which is
imported to the main file. Inside the module, constants are written in all
capital letters and underscores separating the words.
Create a constant.py:
PI = 3.14

Create a main.py:
import constant
print(constant.PI)
Note: In reality, we can not create constants in Python. Naming them in all
capital letters is a convention to separate them from variables, however, it
does not actually prevent reassignment, so we can change it’s value

www.ipzone.wordpress.com
Input and Output

print() Function In Python is used to print output on the screen.


Syntax of Print Function - print(expression/variable)
e.g.
print(122)
Output :-
122
print('hello India')
Output :-
hello India

print(‘Computer',‘Science')
print(‘Computer',‘Science',sep=' & ')
print(‘Computer',‘Science',sep=' & ',end='.')

Output :-
Computer Science
Computer & Science
Computer & Science.
www.ipzone.wordpress.com
PART - 3
Data Types & Debugging

www.ipzone.wordpress.com
Data handling

Most of the computer programming


language support data type,
variables,operator and expression like
fundamentals.Python also support these.

Data Types
Data Type specifies which type of value a
variable can store. type() function is used to
determine a variable's type in Python.
www.ipzone.wordpress.com
Data type continue

Data Types In Python


1. Number
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary

www.ipzone.wordpress.com
Data type continue
Mutable and Immutable Data type
A mutable data type can change its state or contents and
immutable data type cannot.
Mutable data type:
list, dict, set, byte array
Immutable data type:
int, float, complex, string, tuple, frozen set [note: immutable
version of set], bytes

Mutability can be checked with id() method.


x=10
print(id(x))
x=20
print(id(x))
#id of both print statement is different as integer is immutable
www.ipzone.wordpress.com
Data type continue

1. Number In Python
It is used to store numeric values

Python has three numeric types:


1. Integers
2. Floating point numbers
3. Complex numbers.

www.ipzone.wordpress.com
Data type continue
1. Integers
Integers or int are positive or negative
numbers with no decimal point. Integers in Python
3 are of unlimited size.
e.g.

a= 100
b= -100
c= 1*20
print(a)
print(b)
print(c)

Output :-
100
-100
200
www.ipzone.wordpress.com
Data type continue
Type Conversion of Integer
int() function converts any data type to integer.
e.g.

a = "101" # string
b=int(a) # converts string data type to integer.
c=int(122.4) # converts float data type to integer.
print(b)
print(c)Run Code
Output :-
101
122
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue
2. Floating point numbers
It is a positive or negative real numbers with
a decimal point.
e.g.

a = 101.2
b = -101.4
c = 111.23
d = 2.3*3
print(a)
print(b)
print(c)
print(d)Run Code

Output :-
101.2
-101.4
111.23
6.8999999999999995
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue

Type Conversion of Floating point numbers


float() function converts any data type to floating point
number.
e.g.
a='301.4' #string
b=float(a) #converts string data type to floating point number.
c=float(121) #converts integer data type to floating point number.
print(b)
print(c)Run Code

Output :-
301.4
121.0

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue
3. Complex numbers
Complex numbers are combination of a real
and imaginary part.Complex numbers are in the form
of X+Yj, where X is a real part and Y is imaginary part.
e.g.
a = complex(5) # convert 5 to a real part val and zero imaginary part
print(a)
b=complex(101,23) #convert 101 with real part and 23 as imaginary part
print(b)Run Code

Output :-
(5+0j)
(101+23j)

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue
2. String In Python
A string is a sequence of characters. In python we can create
string using single (' ') or double quotes (" ").Both are same in
python.
e.g.
str='computer science'
print('str-', str) # print string
print('str[0]-', str[0]) # print first char 'h'
print('str[1:3]-', str[1:3]) # print string from postion 1 to 3 'ell'
print('str[3:]-', str[3:]) # print string staring from 3rd char 'llo world'
print('str *2-', str *2 ) # print string two times
print("str +'yes'-", str +'yes') # concatenated string

Output
str- computer science
str[0]- c
str[1:3]- om
str[3:]- puter science
str *2- computer sciencecomputer science
str +'yes'- computer scienceyes
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue

Iterating through string

e.g.
str='comp sc'
for i in str:
print(i)

Output
c
o
m
p

s
c

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue

3. Boolean In Python
It is used to store two possible values either true or
false
e.g.
str="comp sc"
boo=str.isupper() # test if string contains upper case
print(boo)

Output
False

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue
4. List In Python
List are collections of items and each item has its own index
value.
5. Tuple In Python
List and tuple, objects mean you cannot modify the contents
of a tuple once it is assigneboth are same except ,a list is
mutable python objects and tuple is immutable Python
objects. Immutable Python d.
e.g. of list
list =[6,9] e.g. of tuple
list[0]=55 tup=(66,99)
print(list[0]) Tup[0]=3 # error message will be displayed
print(list[1]) print(tup[0])
print(tup[1])
OUTPUT
55
9
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue

6. Set In Python
It is an unordered collection of unique and
immutable (which cannot be modified)items.
e.g.
set1={11,22,33,22}
print(set1)

Output
{33, 11, 22}

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Data type continue
7. Dictionary In Python
It is an unordered collection of items and each item
consist of a key and a value.
e.g.
dict = {'Subject': 'comp sc', 'class': '11'}
print(dict)
print ("Subject : ", dict['Subject'])
print ("class : ", dict.get('class'))

Output
{'Subject': 'comp sc', 'class': '11'}
Subject : comp sc
class : 11
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Type conversion
The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called
type conversion.
Python has two types of type conversion.
Implicit Type Conversion
Explicit Type Conversion

Implicit Type Conversion:


In Implicit type conversion, Python automatically converts one data type to another data
type. This process doesn't need any user involvement.
e.g.
num_int = 12 OUTPUT
('datatype of num_int:', <type 'int'>)
num_flo = 10.23 ('datatype of num_flo:', <type 'float'>)
num_new = num_int + num_flo ('Value of num_new:', 22.23)
print("datatype of num_int:",type(num_int)) ('datatype of num_new:', <type 'float'>)
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Type conversion
Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(),float(),str() etc.
e.g.
num_int = 12
num_str = "45"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

OUTPUT
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:', <type 'str'>)
('Data type of num_str after Type Casting:', <type 'int'>)
('Sum of num_int and num_str:', 57)
('Data type of the sum:', <type 'int'>)

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging

Debugging means the process of finding errors, finding


reasons of errors and techniques of their fixation.
An error, also known as a bug, is a programming code
that prevents a program from its successful
interpretation.
Errors are of three types –
• Compile Time Error
• Run Time Error
• Logical Error

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging
Compile time error :
These errors are basically of 2 types –
Syntax Error :Violation of formal rules of a programming
language results in syntax error.
For ex-
len('hello') = 5
File "<stdin>", line 1
SyntaxError: can't assign to function call
Semantics Error: Semantics refers to the set of rules
which sets the meaning of statements. A meaningless
statement results in semantics error.
For ex-
x*y=z
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging
Logical Error
If a program is not showing any compile time error or run time
error but not producing desired output, it may be possible that
program is having a logical error.
Some example-
• Use a variable without an initial value.
• Provide wrong parameters to a function
• Use of wrong operator in place of correct operator required for
operation
X=a+b (here – was required in place of + as per requirement

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging
Run time Error
These errors are generated during a program execution
due to resource limitation.
Python is having provision of checkpoints to handle
these errors.
For ex-
a=10
b=int(input(“enter a number”))
c=a/b
Value of b to be entered at run time and user may enter 0 at run
time,that may cause run time error,because any number can’t be
devided by 0

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging
Run time Error
In Python, try and except clauses are used to handle an
exception/runtime error which is known as exception
handling
try:
# code with probability of exception will be written
here.
a=10
b=int(input(“enter a number”))
c=a/b
except:
#code to handle exception will be written here.
print(“devide by zero erro”)
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging
Available exception in python
Exception Name Description
IOError This exception generates due to problem in input or output.
NameError This exception generates due to unavailability of an identifier.
IndexError This exception generates when subscript of a sequence is out of range.
ImportError This exception generates due to failing of import statement.
TypeError This exception generates due to wrong type used with an operator or a
function.
ValueError This exception generates due to wrong argument passed to a function.
ZeroDivisionError This exception generates when divisor comes to zero.
OverFlowError This exception generates when result of a mathematical calculation exceeds the
limit.
KeyError This exception generates due to non-availability of key in mapping of dictionary.
FOFError This exception generates when end-of-file condition comes without reading
input of a built in function.

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging

In python debugging can be done through


• Print line debugger
• Debugging tool

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging

Print line debugger


– At various points in your code, insert print statements that log the
state of the program
• You will probably want to print some strings with some variables
• You could just join things together like this:
>>>x=9
>>>print 'Variable x is equal to ' + str(x)
Output : Variable x is equal to 9
• … but that gets unwieldy pretty quickly
• The format function is much nicer:
>>>x=3
>>>y=4
>>>z=9
>>>print 'x, y, z are equal to {}, {}, {}'.format(x,y,z)
Output : x, y, z are equal to 6, 4, 8

www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging

Print line debugger


• Python Debugger: pdb
– insert the following in your program to set a breakpoint
–when your code hits these lines, it’ll stop running and launch an
interactive prompt for you to inspect variables, step through the
program, etc.
import pdb
pdb.set_trace()

n to step to the next line in the current function


s to step into a function
c to continue to the next breakpoint
you can also run any Python command, like in the interpreter
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging

Create a.py file with below code and run it in python use n to step
next line.
num_list = [500, 600, 700]
alpha_list = ['x', 'y', 'z']

import pdb
pdb.set_trace() #debugging code
def nested_loop():
for number in num_list:
print(number)
for letter in alpha_list:
print(letter)

if name == ' main ':


nested_loop()

While executing above code whole program will be traced.


Another way is to invoke the pdb module from the command line.
$ python -m pdVbismity:cpoydteh.opny.mykvs.inwww.ipzone.wordpress.com
for regular updates
Debugging

Debugger tool
Another technique for removing an error is code tracing. In this
technique, lines are to be executed one by one and their effect on
variables is to be observed. Debugging tool or debugger tool is
provided in Python for this.
In Python3.6.5, to make debugger tool available, click on debugger
option in debug menu.

www.ipzone.wordpress.com
Debugging

Debugger tool
Then, a box will be opened and a message will come saying DEBUG
ON

Then, we will open our program from file menu and will run it.
www.ipzone.wordpress.com
Debugging

Debugger tool
Then after it will be shown like this in debugger.

Click on STEP button for each line execution one by one and result
will be displayed in output window. When we will get wrong
value, we can stop the program there and can correct the code.

www.ipzone.wordpress.com
PART - 4
Control Statements

www.ipzone.wordpress.com
Control Statements

Control statements are used to control the


flow of execution depending upon the specified
condition/logic.

There are three types of control statements.

1. Decision Making Statements


2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)

www.ipzone.wordpress.com
Decision Making Statement

Decision making statement used to control


the flow of execution of program depending upon
condition.

There are three types of decision making


statement.
1. if statements
2. if-else statements
3. Nested if-else statement

www.ipzone.wordpress.com
Decision Making Statement

1. if statements
An if statement is a programming conditional
statement that, if proved true, performs a
function or displays information.

www.ipzone.wordpress.com
Decision Making Statement
1. if statements
Syntax:
if(condition):
statement
[statements]
e.g.
noofbooks = 2
if (noofbooks == 2):
print('You have ')
print(‘two books’)
print(‘outside of if statement’)
Output
You have two books
Note:To indicate a block of code in Python, you must indent each line of
the block by the same amount. In above e.g. both print statements are
part of if condition because of both are at same level indented but not
the third print statement.
www.ipzone.wordpress.com
Decision Making Statement
1. if statements
Using logical operator in if statement
x=1
y=2
if(x==1 and y==2):
print(‘condition matcing the criteria')

Output :-
condition matcing the criteria
-----------------------------------------------------------
a=100
if not(a == 20):
print('a is not equal to 20')

Output :-
a is not equal to 20

www.ipzone.wordpress.com
Decision Making Statement

2. if-else Statements
If-else statement executes some code if the test
expression is true (nonzero) and some other code if
the test expression is false.

www.ipzone.wordpress.com
Decision Making Statement
2. if-else Statements
Syntax:
if(condition):
statements
else:
statements
e.g.
a=10
if(a < 100):
print(‘less than 100')
else:
print(‘more than equal 100')

OUTPUT
less than 100

*Write a program in python to check that entered numer is even or odd

www.ipzone.wordpress.com
Decision Making Statement

3. Nested if-else statement


The nested if...else statement allows you to check for
multiple test expressions and execute different codes
for more than two conditions.

www.ipzone.wordpress.com
Decision Making Statement
3. Nested if-else statement
Syntax
If (condition):
statements
elif (condition):
statements
else:
statements
E.G.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
OUTPUT
Enter a number: 5
Positive number
* Write python program to find out largest of 3 numbers.
www.ipzone.wordpress.com
Iteration Statements (Loops)

Iteration statements(loop) are used to execute a block


of statements as long as the condition is true.
Loops statements are used when we need to run same
code again and again.
Python Iteration (Loops) statements are of three type :-

1. While Loop

2. For Loop

3. Nested For Loops

www.ipzone.wordpress.com
Iteration Statements (Loops)
1. While Loop
It is used to execute a block of statement as long as a
given condition is true. And when the condition become
false, the control will come out of the loop. The condition
is checked every time at the beginning of the loop.
Syntax
while (condition):
statement
[statements]
e.g.
x=1 Output
while (x <= 4): 1
2
print(x) 3
x=x+1 4

www.ipzone.wordpress.com
Iteration Statements (Loops)
While Loop continue
While Loop With Else
e.g.

x=1
while (x < 3):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)

Output
inside while loop value of x is 1
inside while loop value of x is 2
inside else value of x is 3
*Write a program in python to find out the factorial of a given number

www.ipzone.wordpress.com
Iteration Statements (Loops)
While Loop continue
Infinite While Loop
e.g.
x=5
while (x == 5):
print(‘inside loop')

Output
Inside loop
Inside loop

www.ipzone.wordpress.com
Iteration Statements (Loops)

2. For Loop
It is used to iterate over items of any sequence, such as a list
or a string.
Syntax
for val in sequence:
statements

e.g.
for i in range(3,5):
print(i)

Output
3
4
www.ipzone.wordpress.com
Iteration Statements (Loops)

2. For Loop continue


Example programs
for i in range(5,3,-1):
print(i)

Output
5
4
range() Function Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in
the sequence.

www.ipzone.wordpress.com
Iteration Statements (Loops)

2. For Loop continue


For Loop With Else
e.g.
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")

Output
1
2
3
No Break

www.ipzone.wordpress.com
Iteration Statements (Loops)

2. For Loop continue


Nested For Loop
e.g.
for i in range(1,3):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()

Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20

www.ipzone.wordpress.com
Iteration Statements (Loops)
3. Jump Statements

Jump statements are used to transfer the program's


control from one location to another. Means these are
used to alter the flow of a loop like - to skip a part of a loop
or terminate a loop

There are three types of jump statements used in python.


1.break
2.continue
3.pass

www.ipzone.wordpress.com
Iteration Statements (Loops)
1.break
it is used to terminate the loop.
e.g.
for val in "string":
if val == "i":
break
print(val)

print("The end")

Output
s
t
r
The end
www.ipzone.wordpress.com
Iteration Statements (Loops)
2.continue
It is used to skip all the remaining statements
in the loop and move controls back to the top of
the loop.
e.g.
for val in "init":
if val == "i":
continue
print(val)
print("The end")

Output
n
t
The end

www.ipzone.wordpress.com
Iteration Statements (Loops)
3. pass Statement
This statement does nothing. It can be used when a
statement is required syntactically but the program
requires no action.
Use in loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
In function
It makes a controller to pass by without executing any code.
e.g.
def myfun():
pass #if we don’t use pass here then error message will be shown
print(‘my program')

OUTPUT
My program
www.ipzone.wordpress.com
Iteration Statements (Loops)
3. pass Statement continue
e.g.
for i in 'initial':
if(i == 'i'):
pass
else:
print(i)

OUTPUT
n
t
a
L
NOTE : continue forces the loop to start at the next iteration
while pass means "there is no code to execute here" and will
continue through the remainder or the loop body.

www.ipzone.wordpress.com
PART - 5
Lists

www.ipzone.wordpress.com
It is a collections of items and each item has its own
index value.
Index of first item is 0 and the last item is n-1.Here
n is number of items in a list.

Indexing of list

www.ipzone.wordpress.com
Creating a list
Lists are enclosed in square brackets [ ] and each item is
separated by a comma.
Initializing a list
Passing value in list while declaring list is initializing of a list
e.g.
list1 = [‘English', ‘Hindi', 1997, 2000]
list2 = [11, 22, 33, 44, 55 ]
list3 = ["a", "b", "c", "d"]
Blank list creation
A list can be created without element
List4=[ ]
www.ipzone.wordpress.com
Access Items From A List
List items can be accessed using its index position.
e.g.
list =[3,5,9]
print(list[0]) 3
print(list[1]) 5
print(list[2]) 9
print('Negative indexing') output Negative indexing
print(list[-1]) 9
5
print(list[-2]) 3
print(list[-3])

www.ipzone.wordpress.com
Iterating/Traversing Through A List
List elements can be accessed using looping statement.
e.g.

list =[3,5,9]
for i in range(0, len(list)):
print(list[i])

Output
3
5
9

www.ipzone.wordpress.com
Slicing of A List
List elements can be accessed in subparts.

e.g.
list =['I','N','D','I','A']
print(list[0:3])
print(list[3:])
print(list[:])

Output
['I', 'N', 'D']
['I', 'A']
['I', 'N', 'D', 'I', 'A']

www.ipzone.wordpress.com
Updating / Manipulating Lists
We can update single or multiple elements of lists by giving
the slice on the left-hand side of the assignment operator.
e.g.
list = ['English', 'Hindi', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2:3] = 2001,2002 #list[2]=2001 for single item update
print ("New value available at index 2 : ", list[2])
print ("New value available at index 3 : ", list[3])
Output
('Value available at index 2 : ', 1997)
('New value available at index 2 : ', 2001)
('New value available at index 3 : ', 2002)

www.ipzone.wordpress.com
Add Item to A List
append() method is used to add an Item to a List.

e.g.
list=[1,2]
print('list before append', list)
list.append(3)
print('list after append', list)
Output
('list before append', [1, 2])
('list after append', [1, 2, 3])
NOTE :- extend() method can be used to add multiple item at
a time in list.eg - list.extend([3,4])
www.ipzone.wordpress.com
Add Item to A List
append() method is used to add an Item to a List.

e.g.
list=[1,2]
print('list before append', list)
list.append(3)
print('list after append', list)
Output
('list before append', [1, 2])
('list after append', [1, 2, 3])

NOTE :- extend() method can be used to add multiple item at


a time in list.eg - list.extend([3,4])

www.ipzone.wordpress.com
Add Two Lists
e.g.
list = [1,2]
list2 = [3,4]
list3 = list + list2
print(list3)

OUTPUT
[1,2,3,4]

www.ipzone.wordpress.com
Delete Item From A List
e.g.
list=[1,2,3]
print('list before delete', list)
del list [1]
print('list after delete', list)

Output

('list before delete', [1, 2, 3])


('list after delete', [1, 3])

e.g.
del list[0:2] # delete first two items
del list # delete entire list
www.ipzone.wordpress.com
Basic List Operations

Python Expression Results Description

len([4, 2, 3]) 3 Length


[4, 2, 3] + [1, 5, 6] [4, 2, 3, 1, 5, 6] Concatenati
on
[‘cs!'] * 4 ['cs!', 'cs!', 'cs!', Repetition
'cs!']
3 in [4, 2, 3] True Membership
for x in [4,2,3] : 423 Iteration
print (x,end = ' ')

www.ipzone.wordpress.com
Important methods and functions of List
Function Description
list.append() Add an Item at end of a list
list.extend() Add multiple Items at end of a list
list.insert() insert an Item at a defined index
list.remove() remove an Item from a list
del list[index] Delete an Item from a list
list.clear() empty all the list
list.pop() Remove an Item at a defined index
list.index() Return index of first matched item
list.sort() Sort the items of a list in ascending or descending order
list.reverse() Reverse the items of a list
len(list) Return total length of the list.
max(list) Return item with maximum value in the list.
min(list) Return item with min value in the list.
list(seq) Converts a tuple, string, set, dictionary into list.
www.ipzone.wordpress.com
Some Programs on List
* find the largest number in a list #Using sort
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
#using function definition
def max_num_in_list( list ):
max = list[ 0 ] list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "Max value element : ", max(list1)
for a in list:
print "Max value element : ", max(list2)
if a > max: Output
max = a Max value element : zara
return max Max value element : 700
print(max_num_in_list([1, 2, -8, 0]))
www.ipzone.wordpress.com
Some Programs on List
* find the mean of a list
def Average(lst):
return sum(lst) / len(lst)

# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)

# Printing average of the list


print("Average of the list =", round(average, 2))

Output
Average of the list = 35.75
Note : The inbuilt function mean() can be used to calculate the mean( average ) of
the list.e.g. mean(list)

www.ipzone.wordpress.com
Some Programs on List
* Linear Search
list_of_elements = [4, 2, 8, 9, 3, 7]

x = int(input("Enter number to search: "))

found = False

for i in range(len(list_of_elements)):
if(list_of_elements[i] == x):
found = True
print("%d found at %dth position"%(x,i))
break
if(found == False):
print("%d is not in list"%x)

www.ipzone.wordpress.com
Some Programs on List
* Frequency of an element in list
import collections
my_list = [101,101,101,101,201,201,201,201]
print("Original List : ",my_list)
ctr = collections.Counter(my_list)
print("Frequency of the elements in the List : ",ctr)

OUTPUT
Original List : [101, 101,101, 101, 201, 201, 201, 201]
Frequency of the elements in the List : Counter({101: 4, 201:4})

NOTE :SAME CAN BE DONE USING COUNT FUNCTION.E.G. lst.count(x)

www.ipzone.wordpress.com
PART - 6
Dictionary

www.ipzone.wordpress.com
Dictionary

It is an unordered collection of items where each


item consist of a key and a value.
It is mutable (can modify its contents ) but Key must
be unique and immutable.

www.ipzone.wordpress.com
Dictionary
Creating A Dictionary
It is enclosed in curly braces {} and each item is separated from other item by a
comma(,). Within each item, key and value are separated by a colon (:).Passing
value in dictionary at declaration is dictionary initialization.
e.g.
dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}

Accessing List Item


dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11)
www.ipzone.wordpress.com
Dictionary
Iterating / Traversing through A Dictionary
Following example will show how dictionary items can be accessed through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
11
Informatics Practices
Updating/Manipulating Dictionary Elements
We can change the individual element of dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science'
print(dict)
OUTPUT
{'Class': 11, 'Subject': 'computer science'}
www.ipzone.wordpress.com
Dictionary

Deleting Dictionary Elements


del, pop() and clear() statement are used to remove
elements from the dictionary.
del e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', dict)

Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete', <type 'dict'>)
www.ipzone.wordpress.com
Dictionary

pop() method is used to remove a particular item in a


dictionary. clear() method is used to remove all
elements from the dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
dict.pop('Class')
print('after item delete', dict)
dict.clear()
print('after clear', dict)

Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})

www.ipzone.wordpress.com
Dictionary

Built-in Dictionary Functions


S.No. Function & Description
len(dict)Gives the total length of the dictionary. It is equal to
the number of items in the dictionary.
1

str(dict)Return a printable string representation of a


2 dictionary

type(variable)If variable is dictionary, then it would return a


dictionary type.
3

www.ipzone.wordpress.com
Dictionary

Built-in Dictionary Methods


S.No. Method & Description
1 dict.clear()Removes all elements of dictionary dict
2 dict.copy()Returns a shallow copy of dictionary dict
3 dict.items()Returns a list of dict's (key, value) tuple pairs
4 dict.keys()Returns list of dictionary dict's keys
dict.setdefault(key, default = None)Similar to get(), but will set
5
dict[key] = default if key is not already in dict
6 dict.update(dict2)Adds dictionary dict2's key-values pairs to dict
7 dict.values()Returns list of dictionary dict's values

www.ipzone.wordpress.com
Dictionary

Questions.
1. Create dictionary to store 4 student details with
rollno,name,age field.Search student in list.
2. Create dictionary for month and noofdays for a
year. User is asked to enter month name and
system will show no of days of that month.

www.ipzone.wordpress.com

You might also like