Python Basic For Class XII
Python Basic For Class XII
Class -12
CHAPTER -1
By-
Rakesh Kumar Gupta
PGT CS
SG Public School MGS
Python (a computer language)
• In last class we have learned about Python. In this class we will
learn Python with some new techniques.
• We know that Python is a powerful and high level language and it is
an interpreted language.
• Python gives us two modes of working-
– Interactive mode
– Script mode
ScriptMode
Interactive
Mode
Python (a computer language)
• It is possible to develop various Apps with Python
like–
– GUI Apps
– Web Apps
– Games
– DBMS Apps
– Scripting etc.
Keywords
Keywords are those words which
provides a special meaning to interpreter.
These are reserved for specific functioning.
These can not be used as identifiers,
variable name or any other purpose.
Available keywords in Python are-
Identifiers
• These are building blocks of a program and are used to give names
to different parts/blocks of a program like - variable, objects, classes,
functions.
• An identifier may be a combination of letters and numbers.
• An identifier must begin with an alphabet or an underscore( _
). Subsequent letters may be numbers(0-9).
• Python is case sensitive. Uppercase characters are distinct
from lowercase characters (P and p are different for interpreter).
• Length of an Identifier is unlimited.
• Keywords can not be used as an identifier.
• Space and special symbols are not permitted in an identifier name
except an underscore( _ ) sign.
• Some valid identifiers are –
• Myfile, Date9_7_17, Z2T0Z9, _DS, _CHK FILE13.
• Some invald identifiers are –
• DATA-REC, 29COLOR, break, [Link].
Literals / Values
• Literals are often called Constant Values.
– Literal collections
StringLiterals
String Literal is a sequence of characters that can be a combination
of letters, numbers and special symbols, enclosed in quotation marks,
single, double or triple(“ “ or ‘ ‘ or “’ ‘”).
Graphical View
CORE
DATA TYPE
Floating
Integer Complex String Tuple List Dictionary
Point
Boolean
Variables and Values
An important fact to know is-
– In Python, values are actually objects.
– And their variable names are actually their reference names.
Suppose we assign 10 to a variable A.
A=10
Here, value 10 is an object and A is its reference name.
10
Reference Object
variable
Variables and Values
If we assign 10 to a variable B,
B will refer to same object.
10
Here, we have two variables,
but with same location.
Reference Object
Now, if we change value of B like variable
B=20
Then a new object will be created with 20
• Mutable (Changeable)
– lists, dictionaries and sets.
• Immutable (Non-Changeable)
– integers, floats, Booleans, strings and tuples.
Operators
• The symbols that shows a special behavior or
action when applied to operands are called
operators. For ex- + , - , > , < etc.
• Python supports following operators-
I. Arithmetic Operator
II. Relation Operator
III. Identity Operators
IV. Logical Operators
V. Bitwise Operators
VI. Membership Operators
Operator Associativity
• In Python, if an expression or statement consists
of multiple or more than one operator then
operator associativity will be followed from left-to-
right.
• In above given expression, first 7*8 will be calculated as 56, then 56 will
be divided by 5 and will result into 11.2, then 11.2 again divided by 2
and will result into 5.0.
*Only in case of **, associativity will be followed from right-to-left.
» Empty Statements
• pass
» Simple Statements (Single Statement)
• name=input (“Enter your Name “)
• print(name) etc.
» Compound Statements
• <Compound Statement Header>:
<Indented Body containing multiple simple
statements/compound statements>
• Here, Header line starts with the keyword and ends at colon (:).
• The body consists of more than one simple Python statements or
compound statements.
Statement Flow Control
• In a program, statements executes in sequential
manner or in selective manner or in iterative
manner.
Sequential Selective Iterative
Python -----if Statements
• In Python, if statement is used to select statement
for processing. If execution of a statement is to be
done on the basis of a condition, if statement is to be
used. Its syntax is-
if <condition>:
statement(s)
like -
Python---if-else Statements
• If out of two statements, it is required to select one
statement for processing on the basis of a condition,
if-else statement is to be used. Its syntax is-
if <condition>:
statement(s) when condition is true
else:
statement(s) when condition is false
like -
Nested If -else
Loop/Repetitive Task/Iteration
These control structures are used for repeated
execution of statement(s) on the basis of a condition.
Loop has 3 main components-
1. Start (initialization of loop)
2. Step (moving forward in loop )
3. Stop (ending of loop)
Output
Output
in and not in operator
• in operator-
3 in [1,2,3,4] will return True.
5 in [1,2,3,4] will return False.
– not in operator-
5 not in [1,2,3,4] will return True.
Jump Statements
continue Statement
OUTPUT
String Creation
• String can be created in following ways-
1. By assigning value directly to the variable
String Literal
2. By taking Input
Output
String Operators
• There are 2 operators that can be used to work upon
strings + and *.
»+ (it is used to join two strings)
• Like - “tea” + “pot” will result into “teapot”
• Like- “1” + “2” will result into “12”
• Like – “123” + “abc” will result into “123abc”
word = “RESPONSIBILITY”
• Long lists-
even = [0, 2, 4, 6, 8, 10 ,12 ,14 ,16 ,18 ,20 ] This is a Tuple
• Nested list -
L=[3,4,[5,6],7]
Another method
List Creation
-As we have seen in the example
That when we have supplied
values as numbers to a list even then
They have automatically converted to string
– If we want to pass values to a list in numeric form then we have to write following
function -
eval(input())
L=eval(input(“Enter list to be added “))
eval ( ) function identifies type of the passed string and then return it.
Another example
String Values
Accessing a List
• First we will see the similarities between a List and a String.
• List is a sequence like a string.
• List also has index of each of its element.
• Like string, list also has 2 index, one for forward indexing (from
0, 1, 2, 3, ….to n-1) and one for backward indexing(from -n to -
1).
• In a list, values can be accessed like string.
Forward index 0 1 2 3 4 5 6 7 8 9 10 11 12 13
List R E S P O N S I B I L I T Y
Backward index -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Accessing a List
• len( ) function is used to get the length of a list.
Important 1:membership
operator (in, not in) works
in list similarly as they
work in other sequence.
Important 2: + operator
adds a list at the end of
other list whereas *
operator repeats a list.
Difference between a List and a String
• Main difference between a List and a string is that string is
immutable whereas list is mutable.
• Individual values in string can’t be change whereas it is
possible with list.
Value didn’t
change in string.
Error shown. Value got changed
in list specifying
list is mutable
Traversal of a list
• Traversal of a list means to access and process each and
every element of that list.
• Traversal of a list is very simple with for loop –
[Link](<list>) Append the list (passed in the form of argument) at the end of list
with which function is called.
[Link](<pos>,<item>) Insert the passed element at the passed position.
[Link](<index>) Delete and return the element of passed index. Index passing is
optional, if not passed, element from last will be deleted.
[Link](<value>) It will delete the first occurrence of passed value but does not
return the deleted value.
List Functions and Methods
Function Details
[Link] ( ) It will delete all values of list and gives an empty list.
[Link] (<item>) It will count and return number of occurrences of the passed element.
[Link] ( ) It will reverse the list and it does not create a new list.
[Link] ( ) It will sort the list in ascending order. To sort the list in descending
order, we need to write----- [Link](reverse =True).
Creation of Tuple
• In Python, “( )” parenthesis are used for tuple creation.
() empty tuple
( 1, 2, 3) integers tuple
( 1, 2.5, 3.7, 7) numbers tuple
(‘a’, ’b’, ’c’ ) characters tuple
( ‘a’, 1, ‘b’, 3.5, ‘zero’) mixed values tuple
(‘one’, ’two’, ’three’, ’four’) string tuple
• Long tuple:
• Nested tuple:
Creation of Tuple
tuple() function is used to create a tuple from other sequences.
See examples-
Tuple creation from string Tuple creation from list
• Membership operator:
• Working of membership operator “in” and “not in” is same as
in a list. (for details see the chapter- list manipulation).
• Concatenation and Replication operators:
• + operator adds second tuple at the end of first tuple. * operator repeats
elements of tuple.
Accessing a Tuple
• Accessing Individual elements-
• Traversal of a Tuple –
for <item> in <tuple>:
#to process every element.
OUTPUT
Tuple Operations
• Tuple joining
• Both the tuples should be there to add
with +.
• Tuple Replication-
Tuple Slicing
teachers={“Rajeev”:”Math”, “APA”:”Physics”,”APS”:”Chemistry:”SB”:”CS”}
<dictionary>[<key>] = <value>
By passing List
Nesting in Dictionary
look at the following example carefully in which element of a dictionary is
a dictionary itself.
Updation in a Dictionary
following syntax is used to update an element in Dictionary-
<dictionary>[<ExistingKey>]=<value>
WAP to create a dictionary containing names of employee as key and their salary as
value. Output
Deletion of an element from a Dictionary
following two syntaxes can be used to delete an element form a
Dictionary. For deletion, key should be there otherwise python
will give error.
1. del <dictionary>[<key>]- it only deletes the value and
does not return deleted value.
False
[Link](<>,indent=<n>)
Program to create a dictionary by counting words in a line
Here a dictionary is
created of words
and their frequency.
Dictionary Function and Method
1. len( ) Method : it tells the length of dictionary.
In the above given example, you can see that change is done in
the values of similar keys whereas dissimilar keys got joined with
their values.
Thank you