Class Xi - Full Notes
Class Xi - Full Notes
Class Xi - Full Notes
2. Numeric Literals
The numeric literals in Python can be of integers,
floating point numbers (real numbers) and complex
numbers.
3. Boolean Literals
A Boolean literal in Python is used to represent one of
the two Boolean values ie, True or False.
4. Special Literal
Python has one special literal called as None. It is
used to indicate the absence of a value.
4. Operators
Operators are symbols that represent an operation.
They are tokens that trigger some
computation/action when applied to variables
(operands).
Variables or objects to which computation is applied ,
are called operands.
5. Punctuators
Punctuators are symbols that are used in
programming languages to organize
programmingsentence structures. Most common
punctuators used in Python Programming Language
are
‘, “ , ; , [ ] ,{ },( ), :, = etc.
Expression
An expression is a legal combination of variables,
constants and operators. An expression in python can
be evaluated and which then produces a result.
Eg: (3+4)/10 a+5*2
Statement
A statement is a programming instruction that does
something; ie, some action takes place.
Variables
A variable is a named storage location whose values
can be used and processed during the program run.
Eg: >>>x=3
>>>y=4
>>>z=x+y >>>z=z+1
>>>x=y
>>>y=5
A variable has three main components:- 1.
Identity of the variable
It refers to the address in the memory which does
not change once it has been created. The address
of a variable can be checked using the function id().
Syntax:-
>>>id(variable name)
Eg:- >>>x=100
>>>id(x)
1614996384; which is the address of memory
location storing the value 100.
2. Type of the variable
The type of the variable determines the data type
of it. Data type refers to the type of the data
associated with a variable. The function type()
determines the data type of a variable.
Syntax:-
>>>type(variable name)
Eg: >>>x=100
>>>type(x)
‘class int’
>>>y=100.5
>>>type(y)
‘class float’
>>>z=’haai’
>>>type(z)
‘class str’
3. Value of the variable
To bind value to a variable, we use the assignment
operator(=). This process is termed as building of a
variable.
The concept of assignment operator can be
explained as:
There should be one and only one variable on
the left hand side of the assignment operator.
This variable is called Left-value or L-Value
There can be any valid expression, literal or
variable on the right hand side of the
assignment operator
This expression in called the Right-value or
RValue.
The statement L-Value=R-Value is the
assignment statement.
input () function
In Python, To get input from the user interactively, we can
use the built-in function input().
Syntax:-
Variable-name=input(“<message to be displayed>”)
The input() function always returns a value of String type. But
string values cannot be used for numeric operations. So to
input numeric values, Python offers two functions int() and
float() to be used with input () to convert the values received
through input () function.
Syntax:-
Variable-name=int(input(“<message>”))
Variable-name=float(input(“<message>”))
Multiple Assignments1
1. Assigning same value to multiple variables
We can assign same value to multiple variables in a single
statement in python.
Eg: >>>a=b=c=10
In the above statement, the value 10 is assigned to all three
variables a, b and c.
2. Assigning multiple values to multiple variables
We can assign multiple values to multiple variables in a
single statement in python.
Eg: >>>x,y,z=10,20,30
The above statement will assign the values order wise. Ie
first variable is given first value, second variable the
second value and so on. Ie The above statement will assign
values 10 to x , 20 to y and 30 to z.
Note:
In Python when we want to swap two values, we need to
write
>>> x,y=y,x
The above statement will swap(exchange ) the values of x
and y.
Eg: >>>x=10
>>>y=5
>>>x,y=y,x
After executing the above statement, the values of x and y
are swapped ie
>>>x=5
>>>y=10
4. DATA HANDLING
Python provides a predefined set of data types for handling
the data it uses. Data can be stored in any of the data types.
Data type
It is the way to identify the type of data stored in a variable.
Data can be of many types. Python offers the following
built-in core data types:
Core Data Types
Numbers Sequences Mappings (Sets) None
Integer-----bool Strings Dictionary.
Floating point Lists
Complex Tuples
1. Numbers
Number data types are used to store numeric values in
Python. The Numbers in Python have following core
data types:-
i) Integers
Integers are whole numbers that have no fractional
parts. It can be positive or negative. There are two
types of integers in Python:
a) Integers (signed):- It is the normal integer
representation of whole numbers. Python 3.x
provides a single data type called int to store any
Integer; whether big or small.
b) Boolean:- These represent the truth values False
and True. The Boolean type is a subtype of
integers as the Boolean values (True or False)
represents 1 or 0 respectively. It is represented
by the data type bool.
ii) Floating point Numbers
A number having fractional part is a floating point
number. For eg: 3.14159 is a floating point number.
The data type used to represent a floating number
is float.
The two advantages of floating point numbers over
integers are:
They can represent values between the
integers.
They can represent a much greater range of
values.
Disadvantage over integers:-
Floating point numbers are usually slower
than integer operations.
iii) Complex Numbers
A complex number is of the form a+bi where i is an
imaginary number.
Python represents complex numbers in the form of
a+bj. ie to represent imaginary number python
uses
‘j’ in place of traditional ‘i’.
For eg: x=0+3.1j
y=1.5+2j
The data type used to represent a complex number
is complex .
2. Sequence Data types
i) Strings
A string is a character or a group of characters
enclosed with in single, double or triple quotes. In
Python 3.x, each character stored in a string is a
Unicode character. Unicode is a system designed to
represent every character from every language. The
data type used to represent a string is str.
ii) Lists
A list in Python represents a list of comma
separated values of any data type enclosed between
square brackets. Eg: a=[1,2,3,4]
B=[‘a’,’e’,’i’,’o’,’u’]
C=[1,100.45,’hai’,’r’] iii)
Tuples
Tuples are represented as group of comma-separated
values of any data type with in simple parentheses.
Eg: t=(1,2,3,4)
A=(1,’a’,’e’,100.5)
3. Mappings i) Dictionary
The dictionary is an unordered set of comma
separated key:value pairs with in curly-brackets {
}. Eg: d={‘a’:1,’e’:2,’i’:3,’o’:4,’u’:5}.
2. Relational Operators
Relational operators determine the relation among
different operands. Python provides six relational
operators for comparing values (thus also called
comparison operators). If the comparison is true, the
relational expression results into the Boolean value True. If
the comparison is false, the relational expression results
into the Boolean value False.
The six relational operators are:
< (less than) > (greater than) <=(less than or equal to)
>= (greater than or equal to) ==(equal to)
!= (not equal to)
Example
Expression
An expression in Python is any valid combination
of operators, literals and variables. The
expressions in python can be of 5 types:- 1.
Arithmetic Expression a+b-c
2. Relational expression a<=b
3. Logical expression a and b not c
4. String ‘hello’+’welcome’
5. Compound a+b>c or a*b<c*d
DEBUGGING
Debugging refers to the process of locating the
place of error, cause of error and correcting the code
accordingly.
ERRORS IN A PROGRAM
An error is sometimes called a ‘bug’. There are broadly
three types of errors.
1. COMPILE-TIME ERRORS
2. Run-time errors
3. Logical errors.
1. Compile time errors
Errors that occur during compile time are compile time
errors. When a program compiles, its source code is
checked for whether it follows the programming
language’s rules or not.
There are two types of compile time errors.
1. Syntax error
Syntax errors occur when rules of a
programming language are violated. Eg: x <--
Y*Z
2. Semantic error
It occurs when statements in a program are not
meaningful. Eg: X * Y=Z
2 Run-time errors
Errors that occur during the execution of a program are run
time errors. These errors are harder to detect. Some
runtime errors stop the execution of the program.
3 Logical errors
Sometimes, if there is no error during compile time and run
time, the program code doesn’t work. This is because of the
programmer’s mistaken analysis of the problem he/she is
trying to solve. Such errors are called logical errors.
Flow of Control Types of Statements in Python
Statements are the instructions given to the computer to
perform any kind of action; be it data movements and be it
making decisions or be it repeating actions. Python
statements can be of three types:-
1. Empty statement (Null statement)
The simplest statement is the empty statement. i.e, a
statement which does nothing.In python an empty
statement is the ‘pass’ statement. Whenever python
encounters a pass statement, Python does nothing and
moves to the next statement in the flow of control.
2. Simple Statement
Any single executable statement is a simple statement
in python. For e.g.
print(“hello”) n=input(“Enter
Name”) .
3. Compound statement
A compound statement represents a group of
statements executed as a unit. The compound
statements of python are written in a specific pattern
as follows:-
<compound statement header>:
<intended body containing simple or multiple
statements>
Statement Flow Control
In a program, statements may be executed
sequentially, selectively or iteratively. Every
programming language provides constructs to support
sequence, selection and iteration.
1. Sequence Construct
In this construct, the statements are being executed
sequentially. This represents the default flow of
statement.
Every python program begins with the first
statement of the program. Then each statement in
turn is executed. When the final statement of the
program is executed, the program is done. Sequence
is the normal flow of control in a program.
2. Selection Construct
In this construct, the execution of statements
depending upon a condition-test. If a condition
evaluates to True, a set of statements is executed,
otherwise another set of statements is executed..
This construct is also known as Decision construct
because it helps in making decision about which set
of statements is to be executed.
3. Iteration Construct
In this construct, repetition of a set of statements
depending on a condition test. A set of statements
are repeatedly executed (again and again) until a
condition becomes False and When the condition
becomes False, the repetition stops. This construct is
also known as Looping Construct.
if condition:
statements elif
condition:
statements elif
condition:
statements
.
.
.
Else:
Statements
4. The Nested if statement
If <condition>:
If <condtion>:
Statements Else:
statements
Else:
If <condtion>:
Statements Else:
statements
Iteration/Looping Statements
The iteration statements or looping statements allow a set of
instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called
loops. Python provides two kinds of loops:- for loop and
while loop which represents two categories of loops. They
are
1. Counting loops:- the loops that repeat a certain number
of times. Python’s for loop is a counting loop
2. Conditional loops:- the loops that repeat until a certain
condition become False. Python’s while loop is a
conditional loop.
The for loop
The Synatx of a for loop is as given below:- for
<control variable> in <sequence>:
Body-of-Loop // Statements to repeat.
A for loop in Python is processed as:
Step 1: The loop variable is assigned the first value in the
sequence.
Step 2: All the statements in the body of for loop are
executed with assigned value of a loop variable
Step 3: Once step 2 is over, the loop variable is assigned to
the next value in the sequence and the loop body is
executed (ie step 2 repeated) with the new value of the
loop variable.
Step 4: This continues until all values in the sequences are
processed.
Note:-
1. for loop ends when the loop is repeated for the last
value of the sequence.
2. The for loop repeats n number of times, where n is the
length of the sequence given in for loop’s header.
The range() function
The range() function of Python in normally used with the
python for loop. It generates a list which is a special
sequence type. The common use of range() is in the
following forms:-
1. range(n):- This type of range() function creates a list
from 0 to n-1; where n is an integer.
Eg: range(5) produces a list [0,1,2,3,4]
2. range(<lower limit>, <upper limit>):- This range()
function will produce a list having values from l,
l+1,l+2,-------u-1.(l and u being integers). Eg:
range(0,5) produce a list [0,1,2,3,4]
Range(5,10) produce a list [5,6,7,8,9]
3. range(<l>,<u>,<stepvalue>):- This type of range()
function will produce a list having values as l,l+s,l+2s,-
----<=u-1.
Eg:- range(0,10,2) will produce a list [0,2,4,6,8]
range(10,50,10) will produce a lsit [10,20,30,40]
Note:-
I. In a while loop, control variable should be
initialized before the loop begins, as an
uninitialized variable cannot be used in an
expression.
II. If the update expression is missing inside a while
loop, then such types of loops are called endless
loops or infinite loops.
Eg: i=1
while i<=10:
print(i)
HW.
1. Write a python program to print the series from 1
to 100 using while loop.
2. Write a python program to print the first ‘n’ even
series using while loop.
3. Write a python program to find the sum of first ‘n’
natural numbers using while loop
Note:
• Nested loop is one loop inside another loop
• Once the condition of the outer loop is true,
the control is transferred to the inner loop,
first the inner loop is terminated and then the
outer loop terminates.
• The inner loop must have a different name for
its loop counter variable so that it will not
conflict with the outer loop.
JUMP Statements
Jump statements are used to transfer the program
control flow unconditionally. Python offers two
jump statements to be used with in loops to jump
out of loop iterations. The jump statements are,
1. break
The break statement enables a program to skip
over a part of code. When the break statement
gets executed, it terminates the execution from the
smallest enclosing loop and then the control
reaches to the statement immediately following
the loop.
2. continue
The continue statement forces the next iteration of
the loop to take place, by skipping any code in
between. The program control resumes (continues)
the next iteration of the loop after executing the
continue statement.
HW
1. WAP to input a digit (0-9) and print it in words.
2. WAP to print the first ‘n’ odd numbers in
descending order.
3. Write a program to print the following pattern
4321
432
43
4
1
1 1
11 1
111 3
1111 17
6. STRING MANIPULATION
In python, a group of characters enclosed
between single or double quotation marks is
known as a string.
Creating Strings
Strings are the most popular data types in python. We can
create them by simply enclosing characters in single, double,
or triple quotes. Python treats single quotes the same as
double quotes. Triple quotes are generally used to represent
multi line strings.
An empty string is a string that has 0 character.
Example: >>> str1=”Hello world”
>>>str2= ‘Python Programming’
Special String Operators
1. Concatenation operator (+)
The ‘+’ operator creates a new string by concatenate
(joining) two operand strings.
>>>’1’+’1’ results ‘11’
>>>’A’+’pple’ results ‘Apple’
>>>’tea’+’ pot’ results ‘tea pot’
>>>”123”+”abc” results “123abc”
Note:- We cannot combine numbers and strings as operands
with a ‘+’ operator.
Eg:>>> ‘111’ + 1 is an invalid operation
>>> ‘abc’ + 3 is an invalid operation
2. Replication operator (*)
The ‘*’ operator creates a new string by repeating
multiple copies of the same string.
Eg: >>> ‘abc’ * 3 returns ‘abcabcabc’
>>>’1’ * 2 returns ‘11’
>>> ‘@’ * 5 returns ‘@@@@@’
Note:- While using replication operator, one operand must
be string type and other must be of number type. It cannot
work with both operands of string type.
3. Membership Operators
There are two membership operators for strings. These
are in and not in.
a) in :- It returns True, if a character or a substring
exists in the given string: False otherwise
b) not in:- It returns True, if a character or a substring
does not exist in the given string; False otherwise
Both membership operators require that both
operands used with them are of string type.
Syntax:
<character/substring> in <String>
<character/substring> not in <String>
Eg: >>>’a’ in ‘abcd’ returns True
>>>’’Jap’ in ‘’Japan” returns True
>>>’aa’ in ‘Hello’ returns False
>>>’’1234’ not in ‘12345’ returns False
>>> ‘’jap” not in “Japan” returns True Traversing
a String
Traversing a string means accessing all the elements of the
string one after the other by using the subscript or index
value.
Each character in a string has an index value which starts
from 0 and ends with length-1.(string length: total no of
characters in the string)
Individual elements can be accessed by specifying string
variable name along with index value, enclosed in square
brackets.
Example: s=”Hello World”
>>>s[0] represents the character ‘H’
Character Representation in a string
S=”Python Programming”
Forward 01 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1
indexing( 0 1 2 3 4 5 6 7
positive
index)
String S Py t ho n P r og r a m mi n g
Backward - - - - - - - - - - - - - -
indexing 1 1 1 1 1 9 8 7 6 5 4 3 2 1
(negative 4 3 2 1 0
index)
0 1 2 3 4 5 6
a m a z i n g
-7 -6 -5 -4 -3 -2 -1
Then,
str[0:7] will return string slice as
‘amazing’ str[0:3] will return ‘ama’
str[2:5] will return ‘azi’
str[-7:-3] will return ‘amaz’ str[-5:-1]
will return ‘azin’
Note:- In a string slice, the character at last index is not
included in the result.
2. In a string slice, slicing range in the form str[ : m], where
m is the ending index and starting index is missing;
python will consider the starting index as 0. Then it will
extract the substring from beginning until the last
index1 .(m-1)
Str [ :7] will return ‘amazing’
Str[: 5] will return ‘amazi’
3. In a string slice, slicing range in the form str[n: ], where n
is the starting index. Here for the missing last index,
python will consider the length of the string. Then it will
extract the substring from starting index to length of the
string.
Str[3:] will return ‘zing’
Str[5:] will return ‘ng’
4. For any index n, str[:n] + str[n:] will give the original
string.
Str[:7] + str[7:] will give the string ‘amazing’
Syntax:- <string>.split(character/string)
20 partition():- This method (function) splits the string
at first occurrence of separator and
returns a tuple containing three
items. They are
The part before the separator
The separator itself
The part after the separator
Syntax:- <string>.partition(separator/string)
7.LIST MANIPULATION
List is a collection of comma-separated heterogeneous (different
types) values that are enclosed with in square brackets. It is a
sequenced data type in Python.
Creating a list
Syntax:-
<list-name>=[value1, value2, value3,----]
Eg: >>>list1=[10,20,30,40] #list of integers
>>>list2=[“blue”,”red”,”orange”,”green”] # list of strings
>>>list3= [‘a’,’e’,’I’,’o’,’u’] # list of characters
>>>list4=[10,”red”,450.60,’a’,100.3] # list of multiple data types
>>>list5=[10,[1,2,3,4],20,40] # a list containing another list- Nested
List.
>>>list6=[ ] # empty list – list with no elements
Traversing a list
Traversing a list means accessing each element of a list. Traversing
can be done in two ways:-
1. Using in operator inside for loop
The elements of a list can be accessed individually using for
loop as follows:-
2. Using range() function
The range() function can also be used for accessing the
individual elements in a list as follows:-
LIST OPERATIONS
Python provides some basic operations which can be performed on
lists as follows:-
1. Concatenation (+)
It is a process in which multiple sequences/lists can be
combined together with the help of concatenation operator
(+). Python allows adding (joining) of two lists using +
operator. For eg:-
2. Replication (*)
The replication operator(*) replicates the list for a specified
number of times.
3. Membership operators (in & not in)
Membership testing is an operation carried out to check
whether a particular element is a member of that list or not.
LIST FUNCTIONS AND METHODS
Python offers may built-in functions and methods for list
manipulation. The following are the list manipulation methods in
Python.
1. len() :- It returns the length of its argument list. i.e, it returns
the total number of elements in the list passed. Syntax:-
len(<list>)
2. index () :- This function returns the index of first matched item
from the list.
Syntax: - <list>.index (Item)
3. append():- The append() method adds a new item to the end
of the list.
Syntax:- <list>.append(<item>)
4. extend ():- This method is used for adding multiple elements
(given in the form of a list) to an already existing list. Syntax: -
<list>.extend (<list>)
5. insert () :- This function can be used to insert a new element
at a specified index. It takes two arguments: one is the index
where an item is to be inserted and other is the item itself.
Syntax:- <list>.insert(index_number, item)
6. count() :-This function returns the number of occurrences of a
particular item present in the list. Syntax :-
<list>.count(<item>)
7. reverse():- This function reverses the order of elements in a
list. It places a new value ‘in place’ of an item that already
exist in the list. i.e, it does not create a new list Syntax
:- <list>.reverse()
8. clear() :- This method removes all items from the list. It
doesn’t take any parameters. It only empties the given list. It
doesn’t return any value. Syntax:- <list>.clear()
9. sort() :- This function sorts the items of the list either in
ascending order or in descending order. The default order is
ascending.
Syntax:- <list>.sort()
To sort a list in descending order we can write the sort ()
function as
<list>.sort(reverse=True)
10 sorted ():- The sorted() function takes the name of the
list as an argument and returns a new sorted list with
sorted elements in it. Syntax:- sorted(<list>)
Deletion operations in a List
Python provides functions for deleting or removing an item
from a list. There are three methods for deletion
1. If index of the item is known, use pop() or del statement
2. If the element is known, not the index, remove() can be
used
3. To remove more than one element, del with list slice can be
used.
11. pop() :- It removes the element from a specified index
and also returns the element which was removed.If no index
value is provided in pop() function , then the last element is
deleted from the list.
Syntax:- <list>.pop(index)
12. remove():- It is used when we know the element to be
deleted but not the index of the element.
Syntax:- <list>.remove(<element>)
13. del statement:- It removes a specified element or a
range/slice of element from the list. Syntax:- del
list[range/slice] The max(), min() and sum() functions
max() :- It returns the element with a maximum value from
the list.
Syntax:- max(<list>)
min():- It returns the element with a minimum value from the
list.
Syntax:- min(<list>) sum():- It returns the sum of all
elements from the list.
Syntax:- sum(<list>)
TUPLES
Tuple is a sequence data type in python which is similar to a list.
A tuple consists of different types (heterogeneous) of values separated
by commas and are enclosed with in simple parentheses.
The main difference between lists and tuples are:
Lists are enclosed with in square brackets [], and their elements and size
can be changed; while tuples are enclosed with in simple parentheses (),
and their elements cannot be updated.
Creating Tuples
A tuple is enclosed in parentheses () for creation and each item is
separated by comma.
Creating tuple with a single element
To create a tuple with a single element, we have to include the final
comma. The final comma is mandatory, otherwise it is not considered as
a tuple, rather treated as a string or an integer.
WAP to create a tuple by accepting user input.(use tuple () function)
1. Slicing
Slicing is used to retrieve a subset of values. A slice of a tuple basically
its sub-tuple.
Syntax:-
Tuple-name [start: stop: step-value]
Where start is the starting point
Stop is the ending point
Step is the step-size (stride)
2. Tuple Addition(concatenation)
New elements can be added to a tuple using ‘+’ operator.
3. Tuple Multiplication(Replication)
The operator (* ) is used for replication of the tuple
4. Membership operators (in and not in)
The in operator checks whether a given element is contained in a
tuple. It returns True if element is present in the tuple. Otherwise it
returns False.
The not in operator returns True, If the element is not found in the
tuple. Otherwise it returns False.
2. Immutable types
The immutable types are those types that can never change
their value in place. The immutable data types in python are
Numbers (Integers, floating point and booelan), Strings and
Tuples.
Note:-
Mutability means that, new value can be stored in the same
memory address as and when we want. But in immutable
types we cannot update the value once it is defined.
DICTIONARY
Dictionary is a very versatile data type in Python. It is an
unordered collection of items where each item is represented
as a key: value pair.
Features of a dictionary
1. Each key map to a value. The association of a key and a value
is called a key-value pair.
2. Each key is separated from its value by a colon (:), the items
are separated by commas, and the entire dictionary is
enclosed with in curly brackets. { }
3. Keys are unique (Immutable types) with in a dictionary while
values may not be.
4. The value of a dictionary can be of any type, but the keys
must be of an immutable types such as numbers, strings or
tuples.
5. Dictionary is a Mutable type. We can add new items or
change the value of existing items.
Creating a dictionary
A dictionary can be created by placing items as key: value pairs
inside curly braces separated by comma.
Syntax:
<dictionary_name> =
{key1: value1, key2:value2, key3:value3, key n: value n}
Methods to create a dictionary
Method 1:-
To create an empty dictionary, put two curly braces.
>>>d1 = { }
>>>type(d1)
<class ‘dict’>
Method 2:-
To create a dictionary, key-value pairs are separated by comma
and are enclosed in curly brackets, { }
Method 3:- using built-in Function dict()
The function dict() is used to create an empty dictionary, that is
a dictionary with no items.
Accessing Elements in a dictionary
To access dictionary elements, we can use the square brackets
along with the key to obtain its corresponding value. Traversing
a Dictionary
Traversing a dictionary means accessing each element of a
dictionary. This can be done by using a for loop.