Class12 Python
Class12 Python
Table of Contents
Intro to Python
Tokens in Python
Loops
Strings
Lists
It uses interpreter to convert the source code into machine language. ( An interpreted language )
Python is portable and platform independent i.e. it can run on various operating systems and hardware platforms. ( A
cross-platform language )
For instance, whenever you are using a loop or defining a function, make sure the lines inside the loop or function
definition are properly indented.
INTRODUCTION TO PYTHON
1. Interactive mode
2. Script mode
1. Keywords
Keywords are reserved words in Python ( or any programming language to say ). They have specific meaning to python
interpreter.
We use a keyword in our program only for the purpose it has been defined. And they should be used with exactly as they have
been specified in the table below.
as elif if or yield
2. Identifiers
Identifiers are names used to identify a variable, function or other entities in a program.
The name can only use combination of characters a-z, A-Z, 0-9 or underscore(_).
An identifier cannot start with a digit. It can begin with an uppercase or lowercase alphabet or an underscore (_).
3. Variables
Variable in Python refers to an object – an item or element that is stored in the memory. And It is uniquely identified by a name
(identifier).
In Python we use assignment statement to create new variables and assign specific values to them.
country = 'India'
total_ppl = "1.5 billion"
avg_age = 28.4
South = ['TN','KL','KA','AP','TL']
4. Punctuators
Punctuators are symbols that are used to organise sentence structure.
5. Operators
An operator is used to perform specific mathematical or logical operation on values.
Operators are categorised into 5 types as mentioned below–
Arithmetic Operators
Operator Operation
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
// Floor Division
** Exponent
Notes: (*)
2. Floor Division (//) returns the quotient by removing the decimal part ( thus, in ‘int’ datatype ).
>>> n1 = 15
>>> n2 = 5
>>> n1 / n2
5.0
>>> 5 / 2
2.5
>>> 5 // 2
2
Operator Operation
== Equals to
!= Not equal to
Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.
Operator Description
= Assigns value
x += y x = x+y
x –= y x = x–y
x *= y x = x*y
x /= y x = x/y
x %= y x = x%y
x //= y x = x//y
x ** y x = x**y
notes:
1. ‘==’ operator is different from ‘=’ operator since the first one is relational operator while the latter is assignment operator.
Logical Operators
and Logical AND If both the operands are True, then condition becomes True
or Logical OR If any of the two operands are True, then condition becomes True
not Logical NOT Used to reverse the logical state of its operand
Notes: (*)
2. The logical operator evaluates to either True or False based on logical operands on either side.
By default, all values are True except None, False, 0(zero), empty collections ““, (), [], {} (which are logically False ).
Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or not.
It can also be used to determine whether two variables are referring to same object or not.
Operator Description
is Evaluates True if the variables on either side of the operator point towards the same memory location and False otherwise.
is not Evaluates False if the variables on either side of the operator point towards the same memory location and True otherwise.
>>> num1 = 8
>>> num2 = 10
# (*1)
>>> type(num1) is int
True
# (*2)
>>> num2 = num1
>>> num1 is num2
True
Notes: (*)
1. In the 1st evaluation statement, we are trying to determine whether the value of variable is of certain type or not.
2. In the 2nd evaluation statement, we are checking whether the two variables are referring to same object or not. id(num1)
== id(num2)
Membership Operators
Membership operators are used to check if a value is a member of the given sequence or not.
Operator Description
in Returns True if the variable/value is found in the specified sequence and False otherwise
not in Returns True if the variable/value is not found in the specified sequence and False otherwise
1 ** Exponentiation
6 == , != Equality operators
Notes:
1. Parenthesis can used to override the the precedence of operators. The expression within ( ) is evaluated first.
2. For operators with equal precedence, the expression is evaluated from left to right.
Notes:
Sequence
Notes:
1. String– string is a group of characters ( alphabets, digits or special characters including spaces ) enclosed in single or
double quotation marks.
2. List– list is a sequence of items separated by commas and are enclosed in square brackets [ ].
None is a special data type with a single value. It is used to signify the absence of value in a situation. None supports no
special operations, and neither it False nor 0 (zero).
Type/Class Description
It is a mapping between a set of keys and a set of values. The key-value pair is called an item. A key is separated from its
value by a colon(:) and consecutive items are separated by commas.
Type/Class Description
dict Dictionary
input( ) function is used for taking the input from the user. The user may enter a number or a string but the input( ) function
treats them as string only.
The input ( ) takes what is typed with keyboard, converts it to a string and assigns it to a variable.
Commonly used syntax for converting the data type of the input:
Syntax Use
and we get,
if the user enters any non numeric value in those …… , an error will be generated.
print( ) function
print( ) is used to output data to the screen. ( displaying output in screen ) The print( ) evaluates the expression before
displaying it on screen.
objects object/values to the printed. * indicates that there may be more than one object
Examples:
Statement Output
print(”Hello”) Hello
print(100*8.5) 850.0
LOOPS
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is executed for each of the items in the
range. The values can numeric or elements of string, list, or tuple.
# Example Program
x = [ 1, 2, 3, 4, 5, "END" ]
for i in x:
print(i)
Output:
1
2
3
4
5
END
Output:
1
4
9
16
Output:
1
1
4
9
16
25
Notes:
1. After each iteration, the control condition is tested again and the loop continues as long as the condition remains True.
When this condition becomes False, the statements in the body of loop are not executed.
2. If the condition of the while loop is initially false, the body is not executed even once.
3. The statements the body of the while loop must ensure that the condition eventually becomes False; otherwise the loop will
become an infinite loop, thus resulting in logical error.
The break statement alters the normal flow of execution as it terminates the When a continue statement is encountered, the control
current loop and resumes execution of the statement following that loop. skips the current iteration and jumps to next iteration.
Output:
Number value: 1
Number value: 2
Number value: 3
Number value: 4
Number value: 5
break encountered! Out of loop
Output:
Number value: 1
Number value: 2
Number value: 3
STRINGS
String is a sequence which is made of one or more UNICODE characters. The character can be a letter, digit, whitespace, or
any other symbol. String is immutable.
Notes:
1. Multi line string can be created by enclosing the lines with 3 single or double quotes. ( ‘’’ or “”” )
Positive
0 1 2 3 4 5 6
Indices
String H e l l o w
Negative
-11 -10 -9 -8 -7 -6 -5
Indices
STRING OPERATIONS
1. CONCATENATION
To concatenate means to join. We can concatenate two string using + operator
2. REPETITION
We can repeat string in python using * operator (repetition operator)
3. MEMBERSHIP
We check membership using two membership operators i.e. ‘in’ and ‘not in’
4. SLICING
To access some part of string or substring, we use method called slicing.
#Examples of list
>>> list1 = [ 1, 2, 3, 4, 10 ]
>>> list2 = ['PHY', 'MAT', 'CHE', 'ENG']
>>> list3 = [ 1, 8.0, 'RSQ', [1,2,3], (1,0,0), 't']
Nested Lists
When a list appears as an element of another list, it is called nested list.
Modifying a list
List Operations
1. Concatenation
Note: If we try to concatenate a list with other datatype like string or a tuple, Error will be thrown.
2. Repetition
3. Membership
4. Slicing
>>>list1[2:5]
['B', 'G', 'Y']
>>>list1[:6:2]
['V', 'B', 'Y']
>>>list1[::-1]
['R', 'O' 'Y', 'G', 'B', 'I', 'V']
#Examples of tuples
tup1 = ( 1, 23, 90, 'Hey')
tup2 = ('luft', [1,2,3], (2,))
tup3 = ('a', 'b', 1, 2)
tup4 = (4,)
A key is separated from its value using a colon(:) and consecutive items are separated by commas.
The keys must be unique and of any immutable datatype i.e. number, string or tuple
Mutability of Dictionary
# CONSIDER A DICTIONARY
>>> dict1 = {1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan'}
>>> dict1
{1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan', 5:'Vikram', 6:'DiCaprio'}
>>> dict1
{1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan', 5:'Vikram', 6:'Raju'}