Final Revised Unit-2 Xi Cs - Ip 2020-21 Lets Learn Python Together
Final Revised Unit-2 Xi Cs - Ip 2020-21 Lets Learn Python Together
Together…..
CONTENTS
( Learning Outcomes ) ☺
FEATURES OF PYTHON:
⮚ Python Character Set
⮚ Tokens🡪(Keywords, Identifiers, Literals, Punctuators, Operators)
⮚ Knowledge of Data Types and Operators
⮚ Accepting input from the console
⮚ Assignment statement
⮚ Mutable/Immutable data types
⮚ Introduction to Variable,
⮚ Variable Internals and methods to manipulate it,
⮚ Concept of L-value and R-value of a variable
⮚ Operators and Types and their precedence:
Binary and Unary Operators, Arithmetic Operators,
Augmented Assignment Operators, Relational Operators,
Logical Operators,
⮚ Expressions
PYTHON CHARACTER SET
A set of valid characters recognized by python.
Python uses the traditional ASCII character set. The
latest version recognizes the Unicode character set.
The ASCII character set is a subset of the Unicode
character set.
• Letters :- A-Z , a-z
• Digits:- 0-9
• Special symbols :- Special symbol available over
keyboard
• White spaces:- blank space, tab, carriage return,
new line,
TOKENS
Smallest individual unit in a program is called a token.
They are:
⮚ Keywords
⮚ Identifiers
⮚ Li terals
⮚ Punctuators
⮚ Operators
My funda of remembering Tokens: KILPO 🡪it’s just a shortcut given by me for remembrance ;)
TOKEN🡪 KEYWORDS
Keywords are the words that convey a special meaning to the
language compiler/interpreter. They are reserved for special
purpose and must not be used as normal identifier names.
and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda yield
except
TOKEN🡪 IDENTIFIERS
Identifiers are the fundamental building blocks of a program which
are used to identify a variable, function name, class name,
module name or any object.
RULES OF WRITING AN IDENTIFIER
✔ An identifier starts with a letter A to Z, a to z or an underscore ( _ ) followed by
zero or more letters, underscores and digits (0 to 9).
✔ Identifier name canNOT start with a digit.
✔ Python does NOT allow special characters other than underscore ( _ ).
✔ Identifier must NOT be a keyword of Python.
✔ Python is a case sensitive programming language that is uppercase letters
(capital letters) and lowercase letters (small letters) are treated differently.
• Some valid identifiers : Mymarks , , tv9r ,
Eg. Marks and marks are two different identifiers
file12 Avg_2 in,Python. _no
‘ “ # \ ( ) [] {} @ , :
. ` =
TOKEN🡪 OPERATORS
Operators are tokens that trigger some computation/ action
when applied to variables and other objects in an
expression.
UNARY Unary - , ~ Bitwise complement , not logical
Unary + , OPERATORS
negation
BINARY OPERATORS
ARITHMETIC OPERATORS: +,-,*,/,%,//,**
AUGMENTED ASSIGNMENT OPERATORS: =,
+=,-=,*=,/=,%=,//=,**=
RELATIONAL OPERATORS: >,<,>=,<=,==,!=
LOGICAL OPERATORS: and , or, not
MEMBERSHIP OPERATORS: in, not
in IDENTITY OPERATORS: is, is
not
DATA TYPES
The kind of data for handling the data used in a
program code is the data type.
CORE DATA TYPES
Boolean
Strings Tuple List
MUTABLE AND IMMUTABLE TYPES
• Mutable types:
The mutable types are those whose values can be
changed in place.
Only three types are mutable in Python.
These are: Lists, dictionaries and sets.
• Immutable types:
The immutable types are those that can never
change their value in place.
In python , the following are the immutable types:
Integers, floating point numbers, booleans, strings, tuples
DATA TYPE: Number in Python
It is used to store numeric values.
1. Integers
2. Floating point numbers
3. Complex numbers.
DATA TYPE: NUMBER 🡪 Integer
Integer or int are
positive or negative numbers
with no decimal point.
Integers in Python are of
unlimited size.
Type Conversion to Integer , int( ) function
NOTE:-
The index (also called subscript) is the numbered position of a letter
in the string. In python, indices begin from
0,1,2,…. upto (length-1) in the forward direction and
-1,-2,-3,…..(-length) in the backward direction.
where length is the length of the string.
DATA TYPE: working with STRING examples
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
C omp u t e r S c i e n c e ! ! !
-19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
DATA TYPE: String contd..
Python allows to have two string types:
1) Single line strings (Basic strings)
Text enclosed in single quote ‘India’ or in double quotes “Bharat”
are normally single line strings i.e. they must terminate in one line.
2) Multiline strings
Text spread across multiple lines as one single string.
Two ways of treating multiline strings:-
(i) By adding a backslash at (ii) By typing the text in triple quotation
the end of normal single or apostrophe mark (No backslash
quote/double quote needed at the end of line)
strings.
DATA TYPE: LIST in Python
A list in Python represents a list of comma-separated values of any data type
between square brackets e.g. following are some lists:
LIST is mutable- one can change/add/delete a list’s element)
FORWARD INDEX DIRECTION
0 1 2 3 4 5
10 20 30 40 50 60
-6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION
DATA TYPE: TUPLE in Python
Tuples are represented as list of comma-separated values of any data
type within parentheses. Some examples of tuples:
Tuple is immutable - one cannot change the values of a tuple.
FORWARDINDEX DIRECTION
0 1 2 3 4 5
10 20 30 40 50 60
-6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION
DATA TYPE: DICTIONARY in Python
Dictionary data type is an unordered set of comma-separated key: value
pairs, within { } , with the requirement that within a dictionary, no two keys can be
the same (i.e. there are unique keys within a dictionary). Some examples of
Dictionary:
Value
D = { 10 : ' CS', ' IP': 50
}
Key
CONCEPT OF VARIABLES
• Variable is a name (Named Labels)
given to a memory location that refers
to a value and whose values can be
used and processed during program
run.
• Python variables are created by NOTE:
assigning value of desired data type to Here, marks, Name and
them. The assignment operator = is used Item_price are the named labels
to assign the values from RHS to LHS (variables) with datatype inferred
variable. Eg. Assign integer value to as Integer, String and Float for the
values 100, ‘Agni’, 999.90
create integer variable, string value to a
respectively.
variable to create string variable.
• Python is a type infer language that marks Name
means you don't need to specify the
datatype of variable. Python
100 ‘Agni’
automatically get variable datatype
depending upon the value assigned to Item_price
the variable. 999.90
MEMORY LOCATIONS: Imagine a Table top with different boxes having some
values stored in them. The variables which you will create are the tags (Like
price tags on items in a mall) , which you will place on the top of the boxes.
These tags(variables) will represent (or point)
those boxes with the value assigned to the
variables. Unlike other programming languages,
VARIABLES ARE NOT SORAGE CONTAINERS
in PYTHON
B
1 2 3 4 1 2 3 4
B
10 20 30 40 10 20 30 40
A
15 25 35 45 15 25 35 45
A
100 200 300 400 100 200 300 400
11 22 33 44 11 22 33 44
ASSIGNING VALUES TO VARIABLES
• A Variable is not created ASSIGNING SAME VALUE TO MULTIPLE
VARIABLES
until some value is assigned
to it.
SWAPPING VARIABLES’
ASSIGNING VALUES TO VARIABLES ASSIGNING None VALUES
THROUGH AN EXPRESSION. VALUE (nothing)
TO A VARIABLE
L-VALUE and R-VALUE OF A VARIABLE
Lvalue: Expressions which Rvalue: Expressions which
can be given on the LHS(Left can come on the RHS(Right
Hand Side) of an assignment. hand side) of an assignment.
NOTE: In Python, assigning a
value to a variable means,
variable’s label is referring to that
value
VARIABLE INTERNALS
VARIABLE
DATA
VALUE ID
marks marks
100
100 int 1852878304
More on VARIABLE INTERNALS with example
Here,
⮚ a, b, c are named labels/
variable names /object names a b c
⮚ 10 and 20 are the values
⮚ int is the data type
or <class type> of the
int 10 int 20
variables /objects 1805363264 1805363424
⮚ 1805363264 and 1805363424
are the id of the objects
INPUT through input() function and
OUTPUT through print() statement
❖ To take input from the user, input() function is used. input() function
takes values in string data type.
Syntax of input Function
input()
❖ To print/display the contents on the console(monitor
screen), print() function is used.
Syntax of print Function
print(expression/variable)
NOTE:
Interactive mode
supports displaying of data ,
both with print() function
and also directly writing
the data (contents) on the
NOTE: But, to display in Script mode , print() function is required to
display the data (contents), otherwise nothing is printed
More on INPUT through input() function and
OUTPUT through print() statement…….
# input () takes
string value
by default.
# But price
should be of
numeric value
DYNAMIC TYPING
error
UNARY OPERATORS
Unary + , Unary ~ Bitwise complement , not logical
-, negation
BINARY OPERATORS
ARITHMETIC OPERATORS: +,-,*,/,%,//,**
AUGMENTED ASSIGNMENT OPERATORS: = ,
+=,-=,*=,/=,%=,//=,**=
RELATIONAL OPERATORS: >,<,>=,<=,==,!
= LOGICAL OPERATORS: and , or, not
MEMBERSHIP OPERATORS: in, not in
IDENTITY OPERATORS: is, is not
BITWISE OPERATORS: &(Bitwise AND), ^(Bitwise XOR), |(Bitwise
ARITHMETIC OPERATORS
1) BINARY OPERATOR: requires two A + B , where A and B
are Operands and + is the
values(or operands) to calculate a final
answer Operator
SYMB BINARY DESCRIPTION
OL OPERATOR
+ ADDITION
Operator
returns sum of two values
- SUBTRACTION
Operator
subtracts second operand from first operand
* MULTIPLICATION
Operator
multiplies two values
/ DIVISION
Operator
divides first operand by the second operand and
always return a float value
% MODULO
Operator
produces the remainder of dividing the first
operand by the second operand
// FLOOR DIVISION
Operator
divides the first operand with the second operand
in which the whole part of the result is given in
the output , the fractional part is truncated
NOTE:
In Mathematics,
XY = X**Y in Computer
Science.
X-Y = 1/(X**Y)
ARITHMETIC
OPERATORS
2) UNARY OPERATOR : -A , where A is the
single
operators that act on one operand) Operand and - is the Unary
Unary + Operator
Unary –
⮚ If a=5 then –a means -5
⮚ If a=0 then –a means 0
⮚ If a=-4 then –a means 4
a-=b
-= Subtracts 2 numbers and assigns
the result to left operand
a=a-b Here,
a*=b
%= Modulus 2 numbers and assigns
the result to left operand.
a=a%b a%=b is equivalent to a=a*b
b-=c
//= Floor division on 2 numbers and
assigns the result to left operand
a=a//b a//=b
is equivalent to b=b-c
FOR BOOLEAN
True is equivalent
to 1 and Boolean
False is equivalent
to 0
IDENTIT Y OPERATOR ( is , not)
is
Is, is not are the operators which compares two objects in terms
their memory locations which is their corresponding ide of ntity
(id)
OPERATORS DESCRIPTION EXAMPLE
is It returns True, if two variables point to the
same object, else it returns false
P is Q
is not P
It returns True, if two variables point to different
objects, else it returns false Qnot
P is
int 10
1805363264
R
int 20
Here, P and Q can be an expression or a variable object.
1805363424
EQUALITY OPERATOR (==) and
IDENTITY OPERATOR (is)
a b
char
‘Hi’
58401024
c
char ‘Hi’
64317056
NOTE: c is the input taken from User.
The reason behind this behaviour is that there are few cases where
Python creates two different objects that both store the same value.
These are:
i) Input of strings from the console
ii) Writing integer literals with many digits (very big integers)
iii) Writing floating point and complex literals
MEMBERSHIP OPERATOR
Membership operator tests for Membership in a sequence.
Returns Boolean True or False
OPERATOR DESCRIPTION
in Results to True value if it finds a variable at the LHS of in operator in the
sequence mentioned in the RHS of the in operator, else it returns False
not in Results to True value if it does not find a variable at the LHS of in operator in
the sequence mentioned in the RHS of the in operator, else it returns False
Program
written in
script
mode
Output
visible on
Interpreter
shell
LOGICAL OPERATORS
or , and , not
Logical operators are used to
perform logical operations on the
given two variables or values.
or operator
The or operator combines two expressions, which make its operands.
i) Relational expression as X Y
operands
X
Tea or Coffee X
Y
Y X or Y
False False False
False True True
NOTE: If either Tea or Coffee is True False True
available at home, you can have X Y
it, hence True. If nothing True True True
available out of the two then,
False
ii) Numbers / Strings / Lists as operands
In an expression
operand X orotherwise
Y as result, Y , if first operand
return X.(i.e. expression X) has false, then return
second NOTE: Every integer
X Y X or Y number, float number or
False False Y complex number whether
negative or positive
takes a Boolean value
False True Y True.
True False X Value 0 , 0.0 , 0+0j are
considered False in
Boolean.
True True X
and operator
The and operator combines two expressions, which make its operands.
i) Relational expression as X Y
operands
X
Pen and Paper
Y
X Y X and Y
False False False
NOTE: To write something using pen False True False
and paper, you need both pen and
paper. Then only its True and you will True False False X Y
be able to write. Otherwise, in
absence of anyone out of the two will True True True
be False
Y
CHAINED COMPARISON OPERATOR
Both the
statements
are
equivalent.
Hence, the
output is
same.
OPERATOR PRECEDENCE
Operator Description
** Exponentiation (raised to the power) Highest
~+- Complement unary plus and minus(method
Priority
names for last two are +@ and -@)
*/%// Multiply, divide, modulo and floor division
+- Addition and Subtraction
>> << Right and left bitwise shift
& Bitwise ‘AND‘
^| Bitwise exclusive ‘OR' and regular ‘OR'
<= <> >= Comparison operators
< > == != Equality operators
= %= /= //= += ‘= “= Assignment operators
is , is not Identity operators
in , not in Membership operators
Lowest
not , or , Logical operators
OPERATOR ASSOCIATIVITY
⮚ Left-to-right associativity for all the operators except
exponentiation ** operator
⮚ For eg. multiplication(*),division (/) and floor division
operator(//) have the same precedence,
⮚In same expression🡪 the operator on the left is evaluated first
and then the operator on its right and so on.
Here,
* /
Left to Right Associativity
// have
Same the
as same
precedence
level. So,
by
default left to
Some more exampleson
OPERATORNotASSOCIATIVITY
the
same
Same
NOTE:
as
Here, in the expression / (Division operator )
has the higher priority the + (Addition
operator) in the precedence table.
Not the
same
Same
as EXCEPTIONAL CASE:
If an expression contains **, then
this exponentiation operator has right
Expression= Atom +
• An atom is something that has a value. Identifiers, literals,
Operators
strings, lists, tuples, sets, dictionaries etc.
• An atom is something that has some value.
EXPRESSION: It is referred as a valid combination of
operators and atoms. An expression is composed of one or more
operations.
Types of Expressions
(i) Arithmetic expressions
(ii) Relational expressions
(iii) Logical expressions
(iv) String expressions
HINT:
Imagine a room between the two integer points on
the y axis where the given value will lie.
ceiling
Now, the integer value which comes in the ceiling of
- 2.7
the room is the answer for ceil function . Similarly floor
integer value which comes in the floor of the room is
the answer for floor function.
FUNCTIO Prototype Description
N (General
form)
log math.log
(num,[base])
The log() function
returns the natural
logarithm for num. A
domain error occurs if
num is negative and a
range error occurs if the
argument num is zero.
u*t+(1/2)*f*math.pow(t,2)
ii) |e2y-x|
Ans.
math.fabs(math.exp(2*y)-x)
TIME TO SOLVE……………
Q1) Give☺the output for the Q2) Write the corresponding
Python Expressions from
print statements the mathematical
import math expressions:
print(math.sqrt(81))
print(math.ceil(12.8)) (iii)
Cos(x) - 5x
print(math.floor(12.8)
print(math.ceil(-38.5)) iv) Tan(x)
print(math.floor(-38.5))
q
Bibliograhy and References
• Google
• Wikipedia
• Quora
• geektogeeks
• Book: XI Computer Science
– By Sumita Arora, Dhanpat Rai
Publication 2020 Edition
• Book: XI Informatics Practices
– By Sumita Arora, Dhanpat Rai
Publication 2020 Edition
Swami Vivekananda