11th IP Unit-2 Introduction To Python
11th IP Unit-2 Introduction To Python
UNIT : 2
Introduction To Python
www.ipzone.wordpress.com
PART - 1
Getting Started with Python
www.ipzone.wordpress.com
Python Introduction
www.ipzone.wordpress.com
Features of Python
www.ipzone.wordpress.com
Shortcomings of Python
www.ipzone.wordpress.com
Installing Python
www.ipzone.wordpress.com
Installing Python
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
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
www.ipzone.wordpress.com
Installing Python
www.ipzone.wordpress.com
Installing Python
www.ipzone.wordpress.com
How to work in Python
www.ipzone.wordpress.com
How to work in Python
www.ipzone.wordpress.com
How to work in Python
Python command
prompt >>>
www.ipzone.wordpress.com
How to work in Python
www.ipzone.wordpress.com
Python basics
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
www.ipzone.wordpress.com
Keywords
as finally or
continue if return
del in while
elif is with
except
www.ipzone.wordpress.com
Identifiers
www.ipzone.wordpress.com
Literals
www.ipzone.wordpress.com
Operators
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
www.ipzone.wordpress.com
Operator continue
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
# 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
www.ipzone.wordpress.com
Operators continue
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
//= 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
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
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
www.ipzone.wordpress.com
Barebone of a python program
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
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(‘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
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
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
1. Number In Python
It is used to store numeric values
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
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
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
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
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
www.ipzone.wordpress.com
Unit-2 (Introduction to Python)
Debugging
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)
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
www.ipzone.wordpress.com
Decision Making 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
www.ipzone.wordpress.com
Decision Making Statement
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)
1. While Loop
2. For Loop
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)
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)
Output
1
2
3
No Break
www.ipzone.wordpress.com
Iteration Statements (Loops)
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
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])
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
e.g.
del list[0:2] # delete first two items
del list # delete entire list
www.ipzone.wordpress.com
Basic List Operations
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)
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]
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})
www.ipzone.wordpress.com
PART - 6
Dictionary
www.ipzone.wordpress.com
Dictionary
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'}
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete', <type 'dict'>)
www.ipzone.wordpress.com
Dictionary
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})
www.ipzone.wordpress.com
Dictionary
www.ipzone.wordpress.com
Dictionary
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