0% found this document useful (0 votes)
18 views

Class12 Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Class12 Python

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

📒

Class XII (Python)

Table of Contents

Intro to Python

Tokens in Python

Input and Output

Loops

Strings

Lists

Python is a high level programming language.

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 )

Python is case sensitive.

For example, True and true are not same in python.

Python uses indentation for blocks and nested blocks.

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.

A python source code file uses .py extension.

INTRODUCTION TO PYTHON

Two ways to run a python shell:

1. Interactive mode

2. Script mode

Class XII (Python) 1


TOKENS IN PYTHON
The smallest unit in a program is called a token.

Types of token in python are:

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.

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

*** there are 33 keywords in Python.

2. Identifiers
Identifiers are names used to identify a variable, function or other entities in a program.

The rules for naming an identifier in Python are as follows:

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 (_).

We cannot use special symbols like !, @, #, $, % etc., in identifiers.

It should not be a keyword or reserved word in Python.

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.

Common punctuators used in Python are– ( ) ‘ “ [ ] # { } , : \ .

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

Class XII (Python) 2


Operator Operation

– Subtraction

* Multiplication

/ Division

% Modulus

// Floor Division

** Exponent

Notes: (*)

1. Division (/) always returns the quotient in ‘float’ datatype.

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

Comparison or Relational Operators

Operator Operation

== Equals to

!= Not equal to

> Greater than

< Less than

Greater than or equal


>=
to

<= Less than or 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

Operator Operation Description

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: (*)

Class XII (Python) 3


1. (and, or , not) are to written in lowercase only.

2. The logical operator evaluates to either True or False based on logical operands on either side.

3. Every value is logically either True or False.

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

Precedence of Operators (*)


The following table lists precedence of all operators from highest to lowest.

Order of Precedence Operators Description

1 ** Exponentiation

2 ~,+,– Unary operators

3 * , / , % , // Multiply, divide, Modulo, Floor division

4 +,– Addition, Subtraction

5 <= , < , >, >= Relational operators

6 == , != Equality operators

7 =, %= , /= , //= , –= , += , *= , **= Assignment Operators

8 is , is not Identity operators

9 in, not in Membership operators

10 not , or , and Logical operator

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.

Class XII (Python) 4


3. Unary operators are operators that need only one operand. Examples are unary minus (–), unary plus (+), complement (~),
and lastly only unary logical operator – not

Data Types in Python


Numeric Data types

Type/Class Description Examples

int integer numbers -12, -3, 0, 152, 10

float real or floating point numbers -12.4, 1.0, 89.23

complex complex numbers 3 + 4i, 2 - 2i

bool Boolean data type True , False

Notes:

1. Boolean datatype is a subtype of integer.

a. It is a unique data type, consisting of two constants, True and False.

b. Boolean True value is non-zero, non-null and non-empty value

c. Boolean False is the value zero

Sequence

Type/Class Description Examples

str String a = ‘wild-animal’ b = “792”

list List L = [ 1 , 2, “QR” ]

tuple Tuple J = ( 1, ‘in’, 5.0 )

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 [ ].

3. Tuple– tuple is sequence of items, separated by commas and enclosed in parenthesis ( ).

None – A Special data type

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

NoneType None data type

>>> dem = None


>>> type(dem)
<class 'NoneType'>
>>> print(dem)
None

Dictionary ( Only mapping datatype )

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.

D1= { 1 : “Blue”, 2 : “Yellow”, 3: “Beige” }

Type/Class Description

Class XII (Python) 5


Type/Class Description

dict Dictionary

Input and Output


input( ) function

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.

input ( [ Prompt ] ) – syntax for input ( ) function


Prompt is the string we like to display on screen prior to taking input and it is optional.

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

to take the input as


int(input([prompt])
an integer

to take the input as a


float(input([prompt])
float
it evaluates the input
and assigns it the
most suitable/valid
eval(input([prompt]) data type ( this is
commonly used to
getting lists, tuples as
input )

Suppose we have this statement,


>>> age = int(input(’Enter your age:’))

and we get,

Enter your age: ……

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.

syntax for print( ) is:


print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

print( ) Parameters Description

objects object/values to the printed. * indicates that there may be more than one object

objects are separated by sep. We can use a character, integer, or a string as a


sep (optional parameter)
separator. The default separator is space.
It allows us to specify any string to be appended at the last value. The default is a new
end (optional parameter)
line.
must be an object with write(string) method. If omitted, sys.stdout will be used which
file (optional parameter )
prints objects on the screen.
flush (optional parameter) If True, the stream is forcibly flushed. Default value: False

Examples:

Statement Output

print(”Hello”) Hello

print(100*8.5) 850.0

Class XII (Python) 6


Statement Output

print(”I” + “love” + “my” + “country”) Ilovemycountry

print(”I’m”, 16, “years old”) I’m 16 years old

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.

syntax of the for loop:


for <control-variable> in <sequence/items in range>:
<statements inside body of the loop>

# Example Program
x = [ 1, 2, 3, 4, 5, "END" ]
for i in x:
print(i)

Output:
1
2
3
4
5
END

The Range() function


The range( ) is used to create a list containing a sequence of integers from the given start value up to stop value (excluding
stop value), with a difference of the given step value.

syntax of range( ) function:


range( [ start ], stop[, step ] )

# Example program demonstrating range() function


for i in range(1:5):
print(i**2)

Output:
1

4
9

16

The ‘while’ Loop


The while statement executes a block of code repeatedly as long as the control condition of the loop is true. The control
condition of the while loop is executed before any statement inside the loop.
Syntax of the while loop
while test_condition:
body of while

Class XII (Python) 7


# Example program for while loop
count = 0
while count <= 5:
print(count)
count **= 2

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.

‘break’ and ‘continue’ Statement


Break Statement Continue Statement

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.

# Example program using break statement


n = 0
for n in range(10):
n +=1
if n == 6:
break
print('Number value:', n)
print('break encountered! Out of loop')

Output:
Number value: 1
Number value: 2
Number value: 3
Number value: 4
Number value: 5
break encountered! Out of loop

# Example program using continu statement


n = 0
for n in range(10):
n +=1
if n == 6:
continue
print('Skipped!')
print('Number value:', n)

Output:
Number value: 1
Number value: 2
Number value: 3

Class XII (Python) 8


Number value: 4
Number value: 5
Skipped!
Number value: 7
Number value: 8
Number value: 9
Number value: 10

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.

# Examples for string


>>> str1 = 'Hello world'
>>> str2 = "Hello world"
>>> str3 = '''Hello world'''
>>> str4 = """Hello world"""

# Example for a multi line string


>>> str5 = '''Hello world
it really feels great to be alive again'''

Notes:

1. Multi line string can be created by enclosing the lines with 3 single or double quotes. ( ‘’’ or “”” )

Accessing Characters in a String


Each individual character in a string can be accessed via indexing.

consider a string “Hello world”

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

>>> str1 = 'Hello world'


>>> str1[6]
'w'
>>> str1[2+5]
'o'
>>> str1[-1]
'd'

STRING OPERATIONS
1. CONCATENATION
To concatenate means to join. We can concatenate two string using + operator

>>> str1 = 'Miss'


>>> str2 = 'Maroon'
>>> str1 + str2
'MissMaroon'

***Beware of any whitespaces whenever concatenating the string

2. REPETITION
We can repeat string in python using * operator (repetition operator)

Class XII (Python) 9


>>> str1 = 'Hey'
>>> str1 * 5
'HeyHeyHeyHeyHey'
>>> str1 * 2
'HeyHey'

3. MEMBERSHIP
We check membership using two membership operators i.e. ‘in’ and ‘not in’

>>> str1 = 'Hello World'


>>> 'W' in str1
True
>>> 'Hell' in str1
True
>>> 'WORE' in str1
False
>>> 'Wear' not in str1
True

4. SLICING
To access some part of string or substring, we use method called slicing.

>>> str1 = 'Hello World'


>>> str1[1:5] #Only from index 1 to 4
'ello'
>>> str1[5:10] #Only from index 5 to 9
' Worl'
>>> str1[5:18] #Only from 5 till the end
'World'
>>> str1[7:2] #1st Index greater than 2nd index, Hence empty string
''
>>> str1[:5] #From the start till index 4
'Hello'
>>> str1[6:] #From index 6 till the end of the string
'World'
>>> str1[0:8:2] #From start till index 7 at steps of 2
'HloW'
>>> str1[-5:-1] #Using negative indices
'Worl'
>>> str1[::-1] #If not index is specified and step size is -1
'dlroW olleH' #String is reversed

Class XII (Python) 10


Class XII (Python) 11
LISTS
List is a mutable datatype. A list can have elements of different datatypes such as integer, float, string, tuple or even another
list. Elements of list are enclosed in squared brackets and are separated by comma.

Class XII (Python) 12


# Creating a empty list
new_list1 = [ ]
new_list2 = list() # using list function

#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']

Accessing elements in a list


similar that of accessing elements in a string

>>> list1 = [1, 2, 3.0, 'JIL',[1,2,3], 'MAN', 10]


>>> list1[2]
3.0
>>> list1[4]
[1, 2, 3]
>>> list[-1]
10

Nested Lists
When a list appears as an element of another list, it is called nested list.

>>> list1 = [ 1, 2, 'a', 'm', [7, 8, 9], 1.0]


# the 5th element is also a list - nested list
# accessing elements of nested list
>>> list1[4][0]
7
>>> list1[4][2]
9

Modifying a list

>>> list1 = ['Red','Green','Blue','Pink']


>>> list1[1] = 'Yellow' #modifying list
>>> list1
['Red', 'Yellow', 'Blue', 'Pink']

List Operations
1. Concatenation

# WE CAN JOIN LISTS USING + OPERATOR


>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [6, 7, 8, 9, 10]
>>> list1 + list2
[1, 2, 3, 4, 5, 6, 7, 8, 9 ,10]

Note: If we try to concatenate a list with other datatype like string or a tuple, Error will be thrown.

2. Repetition

# WE CAN REPLICATE A LIST USING REPETITION OPERATOR *


>>>list1 = ['HEY']
>>> list1 * 3
['HEY', 'HEY', 'HEY']

3. Membership

# WE CAN CHECK WHETHER A ELEMENT IS PRESENT OR NOT USING MEMBERSHIP OPERATORS


>>> list1 = ['BLUE', 'GREEN', 'MAGENTA']
>>> 'GREEN' in list1

Class XII (Python) 13


True
>>> 'YELLOW' in list1
False
>>> 'CYAN' not in list1
True

4. Slicing

# Like strings, the slicing method can be applied to lists


>>>list1 = ['V', 'I', 'B', 'G', 'Y', 'O' ,'R']

>>>list1[2:5]
['B', 'G', 'Y']

>>>list1[:6:2]
['V', 'B', 'Y']

>>>list1[::-1]
['R', 'O' 'Y', 'G', 'B', 'I', 'V']

Class XII (Python) 14


Class XII (Python) 15
TUPLES
A tuple is an ordered sequence of elements of different datatypes enclosed in parenthesis and are separated by commas.
Tuple is immutable.

# Creating tuple of element 1


>>> tuple0 = (20) # INCORRECT WAY, this is an integer
>>> tuple1 = (20,) # Now it is a tuple, since comma is added after the element

#Examples of tuples
tup1 = ( 1, 23, 90, 'Hey')
tup2 = ('luft', [1,2,3], (2,))
tup3 = ('a', 'b', 1, 2)
tup4 = (4,)

Class XII (Python) 16


DICTIONARIES
Dictionary is a mapping between a set of keys and a set of values. It is enclosed in curly brackets { }.

key-value pair is called an item.

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

The value can be repeated and be of any datatype.

# Creating a empty dictionary


>>> dict1 = { } # Using curly brackets
>>> dict2 = dict() # Using dict() function

Class XII (Python) 17


# Examples of dictionary
>>> dict3 = {1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan'}

Accessing Items in dictionary

>>> dict1 = {1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan'}


>>> dict1[2]
'Kamal'
>>> dict1[4]
'Khan'
>>> dict1[7] # when key does not exist
Keyerror: 7

Mutability of Dictionary

# CONSIDER A DICTIONARY
>>> dict1 = {1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan'}

# Adding a new item


>>> dict1[5] = 'Vikram'
>>> dict1[6] = 'DiCaprio'

>>> dict1
{1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan', 5:'Vikram', 6:'DiCaprio'}

# Modifying an existing item


>>> dict1[6] = 'Raju'

>>> dict1
{1:'Robin', 2:'Kamal', 3:'Brando', 4:'Khan', 5:'Vikram', 6:'Raju'}

Class XII (Python) 18


Class XII (Python) 19

You might also like