Introduction to Python Programming
Introduction to Python Programming
co Page 1
m/
CHAPTER-1
INTRODUTION TO PYTHON
1.1 Introduction:
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol-
68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
[Link] Page 2
m/
i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
Output: 9
Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\[Link]”).read( ))
ii. Script Mode: In this mode source code is stored in a file with the .py extension
and use the interpreter to execute the contents of the file. To execute the script by the
interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name [Link] , to run the script you have to follow the following
steps:
[Link] Page 4
m/
CHAPTER-2
PYTHON FUNDAMENTALS
2.2 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators
as elif if or yield
All the keywords are in lowercase except 03 keywords (True, False, None).
[Link] Page 5
m/
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.
3. Literal: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.
Literal
String Literal
Numeric Boolean Special
Collections
Eg.
5, 6.7, 6+9j
[Link] Page 6
m/
B. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.
Eg:
"Aman" , '12345'
C. Boolean literal: A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
4. Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator
5. Separator or punctuator : , ; , ( ), { }, [ ]
[Link] Page 8
m/
2.4 Basic terms of a Python Programs:
A. Blocks and Indentation
B. Statements
C. Expressions
D. Comments
B. Statements
A line which has the instructions or expressions.
C. Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.
D. Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.
[Link] Page 9
m/
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment
i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
[Link] Page 10
m/
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)
Creating a variable:
Example:
x=5
y = “hello”
Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print(x)
Example: x=y=z=5
You can also assign multiple values to multiple variables. For example −
x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12
Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.
If you want to know the type of variable, you can use type( ) function :
[Link] Page 12
m/
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x
del y, z
[Link] Page 13
m/
int( ) - constructs an integer number from an integer literal, a float literal or a string
literal.
Example:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example:
[Link] Page 14
m/
object : It can be one or multiple objects separated by comma.
sep : sep argument specifies the separator character or string. It separate the objects/items. By
default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30
[Link] Page 15
m/
CHAPTER-3
DATA HANDLING
3.1 Data Types in Python:
Python has Two data types –
1. Primitive Data Type (Numbers, String)
2. Collection Data Type (List, Tuple, Set, Dictionary)
Data
Types
Primitive Collectio
Data n
Type Data
Type
Numbe Strin
r g
int
float
complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
[Link] Page 16
m/
integer : There are two types of integers in python:
int
Boolean
x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:
>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
float : float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100
[Link] Page 17
m/
complex : Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>[Link]
5.0
>>>[Link]
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
[Link] Page 18
m/
3.2 MUTABLE & IMMUTABLE Data Type:
Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple.
RESULT
OPERATOR NAME SYNTAX
(X=14, Y=4)
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
// Division (floor) x // y 3
% Modulus x%y 2
[Link] Page 19
m/
Example:
>>>x= -5
>>>x**2
>>> -25
RESULT
OPERATOR NAME SYNTAX
(IF X=16, Y=42)
False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y
iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
[Link] Page 20
m/
a. Relational expressions as operands:
X Y X and Y
False False False
False True False
True False False
True True True
X Y X or Y
False False False
False True True
True False True
True True True
[Link] Page 21
m/
b. numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.
X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand
True # is false, otherwise ignores it, even if the second operand is wrong
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
| Bitwise OR x|y
[Link] Page 22
m/
~ Bitwise NOT ~x
Examples:
Let Output:
a = 10 0
b=4
14
print(a & b) -11
print(a | b) 14
2
print(~a)
40
print(a ^ b)
print(a >> 2)
print(a << 2)
v. Assignment operators: Assignment operators are used to assign values to the variables.
OPERA
TOR DESCRIPTION SYNTAX
a. Identity operators- is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]
[Link] Page 24
m/
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)
Output:
False
True
False
Example:
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False
b. Membership operators- in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}
print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)
[Link] Page 25
m/
Output:
True
True
False
True
False
[Link] Page 26
m/
CHAPTER-4
FLOW OF CONTROL
2. Looping or Iteration
3. Jumping statements
[Link] Page 27
m/
There are three types of conditions in python:
1. if statement
2. if-else statement
3. elif statement
2. if-else statement: When the condition is true, then code associated with if statement will
execute, otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3. elif statement: It is short form of else-if statement. If the previous conditions were not true,
then do this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
[Link] Page 28
m/
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
while
Loops in loop
Python
for loop
[Link] Page 29
m/
1. while loop: With the while loop we can execute a set of statements as long as a condition is
true. It requires to define an indexing variable.
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2
2. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)
it generates a list of numbers, which is generally used to iterate over with for loop. range( )
function uses three types of parameters, which are:
a. range(stop)
b. range(start, stop)
Note:
[Link] Page 30
m/
a. range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,
but not including stop value.
Example:
for x in range(4):
print(x)
Output:
0
1
2
3
b. range(start, stop): It starts from the start value and up to stop, but not including
stop value.
Example:
Output:
2
3
4
5
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.
Example:
print(x)
Output:
3
5
7
[Link] Page 31
m/
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and
increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 value
that is 8 here. So, the output is 3, 5, 8.
S.
No. range( ) xrange( )
1. break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i =1 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
print(i) if x == "python":
if i == 3: break
break print(x)
i += 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
[Link] Page 32
m/
2. continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i =0 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
i += 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)
Output: Output:
1 java
2 c++
4
5
6
Syntax:
for loop while loop
[Link] Page 33
m/
Syntax:
for <variable-name> in <sequence>:
for <variable-name> in <sequence>:
statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
[Link] Page 34
m/
3. Write a program to check a year whether it is leap year or not.
year=int(input("Enter the year: "))
if year%100==0 and year%400==0:
print("It is a leap year")
elif year%4==0:
print("It is a leap year")
else:
print("It is not leap year")
[Link] Page 35
m/
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
[Link] Page 36
m/
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")
[Link] Page 37
m/
CHAPTER-5
FUNCTIONS IN PYTHON
5.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
[Link] Page 38
m/
2. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>[Link](49)
7.0
2 ceil( ) Returns the upper integer >>>[Link](81.3)
82
3 floor( ) Returns the lower integer >>>[Link](81.3)
81
4 pow( ) Calculate the power of a number >>>[Link](2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>[Link](-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>[Link](3)
20.085536923187668
Example:
import random
n=[Link](3,7)
[Link] Page 39
m/
Where:
Example:
def display(name):
[Link] Page 40
m/
5.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
[Link] Page 41
m/
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
OUTPUT:
(7, 7, 11)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
[Link] Page 42
m/
OUTPUT:
Hello
None
CHAPTER-6
STRING IN PYTHON
6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.
Each character has its index or can be accessed using its index.
String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, ........... in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1
The index of string in forward direction starts from 0 and in backward direction starts
from -1.
The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index
in backward direction would be –n.)
[Link] Page 44
m/
Output:
kendriya
i. String concatenation Operator: The + operator creates a new string by joining the two
operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
[Link] Page 45
m/
ii. String repetition Operator: It is also known as String replication operator. It requires
two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False
Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya Vidyalaya"
True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False
[Link] Page 46
m/
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
Example:
>>> ord('b')
98
>>> chr(65)
'A'
[Link] Page 47
m/
Program: Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
[Link] Page 48
m/
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
[Link] Page 49
m/
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string
'erutcurts atad'
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus the
index must be valid and out of bounds index causes an error as there is no character to return
from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
[Link] Page 50
m/
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’
S. No. Function Description Example
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first character >>> [Link]()
capitalized. 'Data structure'
3 find(sub,start,end) Returns the lowest index in the string where the >>> [Link]("ruct",5,13)
substring sub is found within the slice range. 7
Returns -1 if sub is not found. >>> [Link]("ruct",8,13)
-1
4 isalnum( ) Returns True if the characters in the string are >>>[Link]( )
alphabets or numbers. False otherwise True
>>>[Link]( )
True
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
5 isalpha( ) Returns True if all characters in the string are >>>[Link]( )
alphabetic. False otherwise. False
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
>>>[Link]( )
False
6 isdigit( ) Returns True if all the characters in the string are >>>[Link]( )
digits. False otherwise. False
>>>[Link]( )
False
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
7 islower( ) Returns True if all the characters in the string are >>> [Link]()
lowercase. False otherwise. True
>>> [Link]()
[Link] Page 51
m/
True
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
True
8 isupper( ) Returns True if all the characters in the string are >>> [Link]()
uppercase. False otherwise. False
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
False
9 isspace( ) Returns True if there are only whitespace >>> " ".isspace()
characters in the string. False otherwise. True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
11 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'
12 lstrip( ) Returns a string after removing the leading >>> str="data structure"
characters. (Left side). >>> [Link]('dat')
if used without any argument, it removes the ' structure'
leading whitespaces. >>> [Link]('data')
' structure'
>>> [Link]('at')
'data structure'
>>> [Link]('adt')
' structure'
>>> [Link]('tad')
' structure'
13 rstrip( ) Returns a string after removing the trailing >>> [Link]('eur')
characters. (Right side). 'data struct'
if used without any argument, it removes the >>> [Link]('rut')
trailing whitespaces. 'data structure'
>>> [Link]('tucers')
'data '
14 split( ) breaks a string into words and creates a list out of it >>> str="Data Structure"
>>> [Link]( )
['Data', 'Structure']
[Link] Page 52
m/
Programs related to Strings:
1. Write a program that takes a string with multiple words and then capitalize the first
letter of each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)
2. Write a program that reads a string and checks whether it is a palindrome string or
not.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1
[Link] Page 53
m/
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
else:
print("String is palindrome")
3. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=[Link]()
print(s1)
elif choice==2:
s1=[Link]()
print(s1)
else:
print("Invalid choice entered")
[Link] Page 54
m/
CHAPTER-7
LIST IN PYTHON
7.1 Introduction:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax:
Example:
[Link] Page 55
m/
mylist = list(("apple", "banana", "cherry")) #note the double round-brackets
print(mylist)
>>> L
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1
['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> L1
[Link] Page 56
m/
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.
>>> L1
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes.
List-name[start:end] will give you elements between indices start to end-1.
The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
[Link] Page 57
m/
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
Method-1:
Output:
s
u
n
d
a
y
Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])
Output:
w
e
d
n
e
s
d
a
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
[Link] Page 58
m/
Joining Operator: It joins two or more lists.
Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
Example:
>>> L1*3
>>> 3*L1
Slice Operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
>>> number[4:20]
>>> number[-1:-6]
[]
>>> number[-6:-1]
[Link] Page 59
m/
>>> number[0:len(number)]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
>>> number[2:4]=["computer"]
>>> number
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
[Link] Page 60
m/
Comparison Operators:
Example:
[Link] Page 61
m/
List Methods:
Consider a list:
company=["IBM","HCL","Wipro"]
S. Function
No.
Description Example
Name
1 append( ) To add element to the list >>> [Link]("Google")
at the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
[Link] (element)
Error:
>>>[Link]("infosys","microsoft") # takes exactly one element
TypeError: append() takes exactly one argument (2 given)
4 index( ) Returns the index of the >>> company = ["IBM", "HCL", "Wipro",
first element with the "HCL","Wipro"]
specified value. >>> [Link]("Wipro")
Syntax: 2
[Link](element)
Error:
>>> [Link]("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list
[Link] Page 62
m/
>>> [Link](2) # Write the element, not index
ValueError: 2 is not in list
5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]
specified position. >>> [Link](2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
[Link](index, element)
>>> [Link](16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
>>> [Link](-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
[]
[Link] Page 63
m/
9 pop( ) Removes the element at >>>company=["IBM","HCL", "Wipro"]
the specified position and >>> [Link](1)
returns the deleted 'HCL'
element. >>> company
Syntax: ['IBM', 'Wipro']
[Link](index)
>>> [Link]( )
The index argument is
'Wipro'
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.
Error:
>>>L=[ ]
>>>[Link]( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
>>> L=[Link]( )
Syntax: >>> L
[Link]( ) ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]
list. >>> [Link]()
Syntax: >>> company
[Link]( ) ['Wipro', 'HCL', 'IBM']
Takes no argument,
returns no list.
12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]
in ascending order. >>>[Link]( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
[Link]( )
To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> [Link](reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
[Link] Page 64
m/
Deleting the elements from the list using del statement:
Syntax:
Example:
>>> L=[10,20,30,40,50]
>>> L
>>> L= [10,20,30,40,50]
>>> L
>>> del L # deletes all elements and the list object too.
>>> L
[Link] Page 65
m/
Difference between del, remove( ), pop( ), clear( ):
S.
del remove( ) pop( ) clear( )
No.
S.
append( ) extend( ) insert( )
No.
Adds an element at the
Adds single element in the end Add a list in the end of specified position.
1
of the list. the another list
(Anywhere in the list)
Takes one list as Takes two arguments,
2 Takes one element as argument
argument position and element.
The length of the list
The length of the list will The length of the list
3 will increase by the
increase by 1. will increase by 1.
length of inserted list.
[Link] Page 66
m/
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
[Link] Page 67
m/
Program-2 Find the second largest number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0]
for i in range(n):
if max<L[i]>second:
max=L[i]
seond=max
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
[Link] Page 68
m/
CHAPTER-8
TUPLE IN PYTHON
8.1 INTRODUCTION:
Syntax:
Example:
>>> T
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T
(3,)
[Link] Page 69
m/
>>> T1=3, # It also creates a tuple with single element
>>> T1
(3,)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
('hello', 'python')
>>> T=(5,10,(4,8))
>>> T
>>> T
[Link] Page 70
m/
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> T1
>>> type(T1)
<class 'int'>
>>> T2
(1, 2, 3, 4, 5)
>>> T3
[Link] Page 71
m/
8.3 Accessing Tuples:
Tuples are very much similar to lists. Like lists, tuple elements are also indexed.
Forward indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with
indexes.
tuple-name[start:end] will give you elements between indices start to end-1.
The first item in the tuple has the index zero (0).
Example:
>>> alpha=('q','w','e','r','t','y')
Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index
>>> alpha[5]
'y'
>>> alpha[-4]
'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain unchanged
TypeError: 'tuple' object does not support item assignment
[Link] Page 72
m/
8.4 Traversing a Tuple:
Syntax:
statement
Example:
Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output:
q
w
e
r
t
y
Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output:
q
w
e
r
t
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
[Link] Page 73
m/
Joining Operator: It joins two or more tuples.
Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
Example:
>>> T1*2
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
Slice Operator:
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3]
('w', 'e')
>>> alpha[3:65]
>>> alpha[-1:-5]
[Link] Page 74
m/
()
>>> alpha[-5:-1]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> alpha[1:5:2]
('w', 'r')
Comparison Operators:
Example:
Consider a tuple:
subject=("Hindi","English","Maths","Physics")
S. Function
No.
Description Example
Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>> len(subject)
len (tuple-name) 4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.
[Link] Page 76
m/
tuple- >>> [Link]("Maths")
[Link](element)
2
5 count( ) Return the number of >>> [Link]("English")
times the value appears.
Syntax: 1
tuple-
[Link](element)
Example:
>>> T=(45,78,22)
>>> T
(45, 78, 22)
Example:
>>> a, b, c=T
>>> a
45
>>> b
78
>>> c
22
Note: Tuple unpacking requires that the number of variable on the left side must be equal
to the length of the tuple.
The del statement is used to delete elements and objects but as you know that tuples are
immutable, which also means that individual element of a tuple cannot be deleted.
[Link] Page 77
m/
Example:
>> T=(2,4,6,8,10,12,14)
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
[Link] Page 78
m/
CHAPTER-9
DICTIONARY IN PYTHON
9.1 INTRODUCTION:
Syntax:
Example:
>>> marks
>>> D
{ }
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee that
[Link] Page 79
m/
Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.
Example:
>>> D1={[2,3]:"hello"}
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
In the above case the keys are not enclosed in quotes and equal sign is used
for assignment rather than colon.
>>> marks
>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
[Link] Page 80
m/
In this case the keys and values are enclosed separately in parentheses and are given as
argument to the zip( ) function. zip( ) function clubs first key with first value and so on.
Example-a
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> marks
Example-b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
>>> marks
Example-c
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
>>> marks
[Link] Page 81
m/
9.3 ACCESSING ELEMENTS OF A DICTIONARY:
Syntax:
dictionary-name[key]
Example:
>>> marks["Maths"]
81
KeyError: 'English'
Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
Syntax:
statement
[Link] Page 82
m/
Example:
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
Syntax:
dictionary-name[key]=value
Example:
>>> marks
>>> marks
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
[Link] Page 83
m/
9.6 DELETE ELEMENTS FROM A DICTIONARY:
Syntax:
del dictionary-name[key]
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> marks
(ii) Using pop( ) method: It deletes the key-value pair and returns the value of deleted
element.
Syntax:
[Link]( )
Example:
>>> marks
>>> [Link]('Maths')
81
[Link] Page 84
m/
9.7 CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:
(i) in : it returns True if the given key is present in the dictionary, otherwise False.
(ii) not in : it returns True if the given key is not present in the dictionary, otherwise
False.
Example:
True
False
>>> 78 in marks # in and not in only checks the existence of keys not values
False
However, if you need to search for a value in dictionary, then you can use in operator
with the following syntax:
Syntax:
Example:
>>> 78 in [Link]( )
True
[Link] Page 85
m/
To print a dictionary in more readable and presentable form.
For pretty printing a dictionary you need to import json module and then you can use
Example:
OUTPUT:
"physics": 75,
"Chemistry": 78,
"Maths": 81,
"CS": 78
dumps( ) function prints key:value pair in separate lines with the number of spaces
Steps:
[Link] Page 86
m/
Program:
import json
L = [Link]()
d={ }
for word in L:
key=word
if key not in d:
count=[Link](key)
d[key]=count
print([Link](d,indent=2))
S. Function
No.
Description Example
Name
1 len( ) Find the length of a >>> len(marks)
dictionary.
Syntax: 4
len (dictionary-name)
2 clear( ) removes all elements >>> [Link]( )
from the dictionary
Syntax: >>> marks
[Link]( )
{}
[Link] Page 87
m/
3. get( ) Returns value of a key. >>> [Link]("physics")
Syntax:
[Link](key) 75
Note: When key does not exist it returns no value without any error.
>>> [Link]('Hindi')
>>>
4 items( ) returns all elements as a >>> [Link]()
sequence of (key,value)
tuples in any order. dict_items([('physics', 75), ('Chemistry',
Syntax: 78), ('Maths', 81), ('CS', 78)])
[Link]( )
Note: You can write a loop having two variables to access key: value pairs.
>>> seq=[Link]()
>>> for i, j in seq:
print(j, i)
OUTPUT:
75 physics
78 Chemistry
81 Maths
78 CS
5 keys( ) Returns all keys in the >>> [Link]()
form of a list.
Syntax: dict_keys (['physics', 'Chemistry',
[Link]( ) 'Maths', 'CS'])
6 values( ) Returns all values in the >>> [Link]()
form of a list.
Syntax: dict_values([75, 78, 81, 78])
[Link]( )
7 update( ) Merges two dictionaries.
Already present elements
are override.
Syntax:
[Link](dictionary2)
Example:
>>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }
>>> [Link](marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}
[Link] Page 88
m/
[Link] Page 89
m/
Python offers the 'in' and 'not in' operators to check the existence of keys within a dictionary. These operators return boolean values, indicating whether a specified key is present. Additionally, the dict.get() method can retrieve values associated with a key or return a default value if the key is absent. This method avoids raising errors when keys do not exist. Moreover, methods like dict.keys() and dict.items() facilitate iteration over keys and the entire dictionary, respectively .
To traverse and modify a dictionary's values, Python allows iterating over keys either by using a for loop directly on the dictionary or by employing the items() method, which provides key-value pairs. During traversal, the value associated with any key can be updated using assignment operators. Modification directly alters the dictionary in-place, providing a seamless approach to updating stored data based on conditions evaluated during traversal .
The dict() constructor in Python provides a versatile way to create dictionaries, supporting multiple input formats for initialization. It can accept lists, tuples, or even separate keys and values as arguments. For example, using the zip() function allows pairing of keys and values conveniently from two sequences. This flexibility aids in constructing dictionaries efficiently from a variety of data inputs, facilitating ease of data manipulation and retrieval .
Mutable data types in Python can be changed after creation; they allow modification without needing to create a new object. Examples include lists, sets, and dictionaries. For instance, you can add elements to a list or change values within it, maintaining the same memory address. In contrast, immutable data types cannot be altered once created; any modification results in a new object. Examples include integers, floats, Booleans, strings, and tuples. If you attempt to modify these, Python creates a new object with a new memory address .
The eval() method in Python is useful for evaluating input strings as expressions, facilitating the creation of lists that retain proper data types like integers or floats without additional parsing. It allows dynamic interpretation of user input, simplifying list creation from complex inputs such as embedded lists or numeric sequences. However, eval() poses security risks if not handled carefully, as executing arbitrary code can lead to vulnerabilities. Careful validation and sanitization of input are essential when employing eval() to ensure safe execution .
Complex numbers in Python, which consist of a real part and an imaginary part, are crucial in scenarios involving electromagnetic waves, quantum mechanics, and vibration analysis. They facilitate calculations involving phase shifts, resonance frequencies, and impedance in electrical circuits. In computational fields, complex numbers support mathematical models where non-real solutions are possible, extending the domain of problems that can be computationally explored .
String immutability in Python implies that any modification to a string results in a new string object. This behavior can lead to performance inefficiencies if excessive string modifications are needed, as each change results in reallocating memory for a new string. However, it provides benefits in thread-safe operations, where shared data integrity is crucial. For extensive text manipulations, alternatives like using a list of characters or employing libraries specifically designed for mutable strings may offer optimized solutions .
The print() function in Python includes parameters such as sep (separator) and end, which allow customization of the output format. By default, print() uses a space character for separating multiple objects and a newline for ending the print output. Modifying these parameters provides more control over how data is displayed. For instance, using a character or string as a separator can enhance data readability or align with specific formatting requirements in reports or logs .
Python supports three main numeric types: integers, floats, and complex numbers, allowing it to handle a wide range of numeric calculations. Floats enable precise calculations involving decimal points and can also represent numbers in scientific notation, which is useful for large scale mathematical computations. Complex numbers in Python, with real and imaginary parts, cater to advanced scientific and engineering calculations that require complex number manipulations .
A Python program to capitalize the first letter of each word in a string involves reading the string and iterating over it to check for spaces. When a space is detected, the next character is capitalized and appended to a new string until the end of the original string is reached. This can be achieved using loops and string concatenation methods to build the new capitalized string .