Class 11 IP Ch-2, 3, 4 Python Programming Basics Notes
Class 11 IP Ch-2, 3, 4 Python Programming Basics Notes
Python is a very popular and easy to learn programming language, created by Guido van Rossum in 1991.
It is used in a variety of fields, including software development, web development, scientific computing, big data
We are using Python 3.7.0. However, one can install any version of Python 3.
Python is a dynamic, high level, free open source and interpreted programming language. It supports object-
In Python, we don’t need to declare the type of variable because it is a dynamically typed language.
For example, x = 10
Features in Python
There are many features in Python, some of which are discussed below –
1. Easy to code: Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, JavaScript, Java, etc. It is very easy to code in python language and anybody
can learn python basics in a few hours or days. It is also a developer-friendly language.
2. Free and Open Source: Python language is freely available at the official website and you can download it. Since it
is open-source, this means that source code is also available to the public. So you can download it as, use it as well as
share it.
3. Object-Oriented Language: One of the key features of python is Object-Oriented programming. Python supports
4. GUI Programming Support: Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python. PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language: Python is a high-level language. When we write programs in python, we do not need to
6. Extensible feature: Python is an Extensible language. We can write us some Python code into C or C++ language
7. Python is Portable language: Python language is also a portable language. For example, if we have python code
for windows and if we want to run this code on other platforms such as Linux, UNIX, and Mac then we do not need to
1
8. Python is Integrated language: Python is also an integrated language because we can easily integrated python
9. Interpreted Language: Python is an Interpreted Language because Python code is executed line by line at a time.
like other languages C, C++, Java, etc. there is no need to compile python code this makes it easier to debug our
code. The source code of python is converted into an immediate form called bytecode.
10. Large Standard Library: Python has a large standard library which provides a rich set of module and functions so
you do not have to write your own code for every single thing. There are many libraries present in python for such as
11. Dynamically Typed Language: Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of this feature we don’t need to
can use any online Python interpreter. The interpreter is also called Python shell.
Execution Modes
Interactive mode Script mode
In the interactive mode, we can type a Python In the script mode, we can write a Python program in
statement on the >>> prompt directly. As soon as we a file, save it and then use the interpreter to execute
press enter, the interpreter executes the statement the program from the file. Such program files have a
and displays the result(s). .py extension and they are also known as scripts.
Working in the interactive mode is convenient for Python has a built-in editor called IDLE which can be
testing a single line code for instant execution. But in used to create programs. After opening the IDLE, we
the interactive mode, we cannot save the statements can click File -> New File to create a new file, and
for future use and we have to retype the statements then write our program on that file and save it with a
to run them again. desired name. By default, the Python scripts are
saved in the Python installation folder.
IDLE- Integrated Development and Learning
Environment.
2
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 (American Standard Code for information interchange) character set
is subset of the Unicode character set.
Letters :– A-Z, a-z
Digits :– 0-9
Special symbols: – Special symbol available over keyboard (! , @, #, $, % ^, & etc.)
White spaces:– Blank space, tab, carriage return (enter key), newline, form feed
Other characters:- Unicode
Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. As Python is case
sensitive, keywords must be written exactly as given in following Table
Punctuators
It is used to implement the grammatical and structure of Syntax. Following are the python punctuators.
Identifiers
In programming languages, 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 should begin with an uppercase or a lowercase alphabet or an underscore sign (_). This may be
followed by any combination of characters a-z, A-Z, 0-9 or underscore (_). Thus, an identifier cannot start with a
digit.
It can be of any length. (However, it is preferred to keep it short and meaningful).
It should not be a keyword or reserved word.
We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Python is a case sensitive language. So uppercase and lowercase identifiers behave differently. For example
Capital A is completely different from small a. So in python language it is not same but in our human language
capital and small letter is same.
3
Valid identifiers Invalid identifiers Reason for invalid
rollno roll no We cannot use blank space between.
ROLLNO 2rollno First letter must be alphabet not a number.
RollNo for Reserved words cannot use.
Roll_NO try Reserved words cannot use.
roll_no roll.no Special symbols cannot use in between.
_rollno roll$no Special symbols cannot use in between.
rollno2 2a First letter must be alphabet not a number.
Variables
Variable is an identifier whose value can change.
Variable is memory location name which can hold a value.
Variable name should be unique in a program.
Value of a variable can be string (for example, ‘b’, ‘Global Citizen’), number (for example 10, 71, 80.52) or any
combination of alphanumeric (alphabets and numbers for example ‘b10’) characters.
In Python, we can use an assignment statement to create new variables and assign specific values to them.
Variables must always be assigned values before they are used in the program, otherwise it will lead to an error.
Wherever a variable name occurs in the program, the interpreter replaces it with the value of that particular
variable.
Python is a type infers language that means you don't need to specify the data type of variable. Python
automatically get variable data type depending upon the value assigned to the variable.
For examples:-
gender = 'M'
message = "Keep Smiling"
price = 987.9
rollno = 1001
Literals
Literals in python can be defined as number, text or other data that represent values to be stores in variables.
Example of string literals Example of integer literals Example of Boolean literals
name = “john” age = 22 result = True
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of For example:-
constants as containers that hold information which cannot be changed later. In python,
Create a constant.py:
constants are usually declared and assigned in a module. Here, the module is a new file PI=3.14
containing variables, functions etc. which is imported to the main file. Inside the module,
Create a main.py:
constants are written in all capital letters and underscores separating the words. import constant
Note: In reality, we cannot create constants in Python. Naming them in all capital letters is a print(constant.PI)
convention to separate them from variables, however, it does not actually prevent
reassignment, so we can change it’s value.
4
Comments
Comments are used to add a remark or a note in the source code.
Comments are not executed by interpreter.
Comments are added with the purpose of making the source code easier for humans to understand.
Comments are used primarily to document the meaning and purpose of source code.
In Python, a single line comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment and the interpreter simply ignores it
while executing the statement.
For example:-
# Following statement display hello world.
print(“hello world”)
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data which a variable can hold
and the operations that can be performed on those data. Following figure shows the data types available in Python.
Number Boolean
Number data type stores numerical values only. Boolean data type (bool) is a subtype of integer.
It is further classified into three different types. It is a unique data type, consisting of two
int, float and complex. constants, True and False.
To determine the data type of the variable using built-in Boolean True value is non-zero.
function type( ). Boolean False is the value zero.
5
Sequences
A Python sequence is an ordered collection of items, where each item is indexed by an integer value.
Three types of sequence data types available in Python are Strings, Lists and Tuples.
String List Tuple
String is a group of characters. List is a sequence of items Tuple is a sequence of items
These characters may be separated by commas separated by commas.
alphabets, digits or special Items are enclosed in square Items are enclosed in
characters including spaces. brackets [ ]. parenthesis ( ).
String values are enclosed either Once created, we can change Once created, we cannot change
in single quotation marks items in the list. items in the tuple.
for example ‘Hello’ Items may be of different data Similar to List, items may be of
or in double quotation marks types. different data types.
for example “Hello” For example :- For example :-
The quotes are not a part of the list1 = [5, 3.4, "New Delhi", 45] tuple1 = (10, 20, "Apple", 3.4, 'a')
string, they are used to mark the
beginning and end of the string
for the interpreter.
We cannot perform numerical
operations on strings, even when
the string contains a numeric
value.
For example :-
str1 = 'Hello Friend'
str2 = "452"
Mapping
Dictionary
Dictionary in Python holds data items in key-value pairs.
Items are enclosed in curly brackets { }.
Dictionaries permit faster access to data.
Every key is separated from its value using a colon (:) sign.
The key value pairs of a dictionary can be accessed using the key.
Keys are usually of string type and their values can be of any data type.
In order to access any value in the dictionary, we have to specify its key in square brackets [ ].
For example:-
dict1 = { 'Fruit' : 'Apple', 'Climate' : 'Cold', 'Price' : 120 }
here ‘Fruit’ ‘Climate’ ‘Price’ are keys
here ‘Apple’ ‘Cold’ 120 are values
6
Operators
An operator is used to perform specific mathematical or logical operation on values. The values that the operator
works on are called operands.
For example, in the expression 10 + num, the value 10, and the variable num are operands and the + (plus) sign is
an operator. Python supports several kinds of operators.
Arithmetic Operators Relational Operators Assignment Operators Logical Operators
Compute two values Compare two values
+ == (equals to) = and
3+2 3==2 a=5 (3==2) and (3!=2)
5 False False and True
False
- != (is not equal to) += or
3-2 3!=2 a=a+1 (3==2) or (3!=2)
1 True or False or True
a +=1 True
* < (less than) -= not
3*2 3<2 a=a-1 not (3==2)
False
or not (False)
6
a-=1 True
not -> reverse the result
/ > (greater than) *= cond1 cond2 And Or
True True True True
3/2 3>2 a=a*1 False False False False
True False False True
a*=1
/ returns decimal point
% - modulus <= (less than or equal to) /= condition not
True False
3%2 3<=2 a=a/1 false True
1 False or
% returns only remainder a/=1
// - Floor division >= (greater than or equal to) %= Uses of And, Or, Not
3>=2 And To check condition in range,
3//2 a=a%1 between and must situation
**=
a = a ** 1
or
a ** = 1
7
Membership operators
Operator Description Example
in Returns True if the variable or value is found in the specified a = [1, 2, 3] a = [1, 2, 3]
sequence and False otherwise
2 in a 4 in a
Output -> True Output -> False
not in Returns True if the variable/value is not found in the specified a = [1, 2, 3] a = [1, 2, 3]
sequence and False otherwise
2 not in a 4 not in a
Output -> False Output -> True
Shift operators
Left shift – bits shift to left side Right shift – bits shift to right side
<< >>
Multiply operation Divide operation
4<<1 4<<2 4<<3 4>>1 4>>2 4>>3
4 * 21 4 * 22 4 * 23 4 / 21 4 / 22 4 / 23
4*2 4*4 4*8 4/2 4/4 4/8
8 16 32 2 1 0
Identity operators
Identity operators in python compare the memory locations of two objects.
id() – It is used to show memory location value of any variable.
print(a==b) print(a==b)
True False
print(a is b) print(a is b)
True False
8
Structure of python programs
Indentation
Indentation refers to the spaces applied at the beginning of a code line. In other programming languages the
indentation in code is for readability only, where as the indentation in python is very important.
Python uses indentation to indicate a block of code or used in block or codes.
Incorrect indentation Correct indentation
A=3 A=3
B=4 B=4
If A > B : If A > B :
print (“A is not greater than B”) print (“A is not greater than B”)
Examples:-
# to display hello world in same line
print("hello world")
output:-
hello world
----------------------------
# to display world in new line
print("hello \n world")
output:-
hello
world
----------------------------
# to display world in same line but one tab key distance
print("hello \t world")
output:-
hello world
9
Python Programming Rules
1. Variables are not storage container in python
Traditional Programming Languages’ Variables Python Variables in Memory
such as c, c++, Java etc
a=3 a=3
Inside RAM memory Inside RAM memory
Variable Value Memory Address Variable Value Memory Address
a 3 1001 a 3 1001
a=4 a=4
Inside RAM memory Inside RAM memory
Variable Value Memory Address Variable Value Memory Address
a 4 1001 a 4 1005
Note:- In c, c++, Java language, will not change memory Note:- In python, will change memory address every
address of a variable every time, when you assign a time of a variable, when you assign a new value in
new value in existing variable. existing variable.
3. Multiple Assignments:-
Assigning same value to multiple variables:- Assigning multiples values to multiple variables:-
a = 10 a = 10
b = 10 b = 20
c = 10 c = 30
#we can also write same above code in one line #we can also write same above code in one line
a = b = c = 10 a, b, c = 10, 20, 30
10
4. Swap Values (Interchange values):-
In other computer language, In python language
to interchange values, we must use third variable t. to interchange values, we need not use third variable t.
a = 10 a = 10
b = 20 b = 20
inside
t=a t = 10 (copy value of a in advance to t) a, b = b, a
a=b a = 20
b=t b = 10
Final values in memory of following variables Final values in memory of following variables
a = 20 a = 20
b = 10 b = 10
5. Python first evaluates the RHS expression and then assign in LHS variable
While assigning values through multiple assignments please remember that Python first evaluates the RHS (right
hand side) expression(s) and then assign to LHS.
Not Broadcast values Broadcast values
a=1 a=1
b=2 b=2
c=3 c=3
inside expression
b=a+4 (b = 1+4 so b = 5) b, c, a = a + 4, b +5, c - 6
c=b+5 (c = 5+5 so c =10) inside expression
a=c- 6 (a = 10-6 so a =4) b, c, a = 1 + 4, 2+5, 3 - 6
print(b) print(b)
print(c) print(c)
print(a) print(a)
Output Output
5 5
10 7
4 -3
11
6. Dynamic binding
Data type of a variable depends /changes upon the value assigned to a variable on each next statement.
Without dynamic binding With dynamic binding
A=5 A=5
A = 10 A = “python”
B=A/2 B=A/2
print (B) print (B)
Output:- Output:-
5 Error – String cannot be divided.
Note:- because last value of A is “python” so this string
data type cannot be divide with 2.
7. Variable Definition
Python, a variable is defined only when you assign some value to it. Using an undefined variable in an expression /
statement causes an error called NameError.
Without variable definition With variable definition
print (a) a = 10
print (a)
output:- output:-
It will display an error. 10
name ‘a’ is not defined.
Note:- we must assign a value in a variable then we can use it.
12
Simple Input and output
input() – It is used to get data from the keyboard. By default it takes input as string datatype. So if you want to
input number then you must convert this string datatypes into numberic datatypes using int() and float().
Syntax:-
variable = input(<prompt to be displayed>)
String input Integer input Float input
name = input(“enter name”) rollno = int ( input ( “enter age” ) ) price = float ( input( “enter price” ) )
enter name raj enter age 17 enter price 85.35
13
print() statement for output
It is used to send output to standard output device, which is normally a monitor.
A print() function without any value or name or expression prints a blank line.
Syntax:- print( “message”, variables, end= ‘ ‘)
Various Examples of print() statements:- Outputs
print(“python is wonderful”) python is wonderful
print(“sum of 2 and 3 is”, 2+3) sum of 2 and 3 is 5
a = 25 Double of 25 is 50
print(“Double of”, a , “is”, a * 2)
print(“My”, “name”, “is”, “Amit.”) My name is Amit.
print(“My”, “name”, “is”, “Amit.”, sep = ‘...’) My... name... is... Amit.
print(“My name is Amit.”) My name is Amit.
print(“I am 16 years old”) I am 16 years old
print(“My name is Amit.”, end =’$’) My name is Amit. $I am 16 years old
print(“I am 16 years old”)
print(“My name is Amit.”, end =’ ’) My name is Amit. I am 16 years old
print(“I am 16 years old”)
note:- we can use end= ‘ ‘ to display outputs of multiple
print() statements in one line.
Following escape characters in print()
\t - It is used to give tab space, approx ½ inch gap.
\n – It is used to display message in next new line.
print(“My name \t is Amit”) My name is Amit
print(“My name \t is \t Amit”) My name is Amit
print(“My name \t is \n Amit”) My name is
Amit
print(“My name \n is \n Amit”) My name
is
Amit
print(“My name \n is \t Amit”) My name
is Amit
14
Operator Precedence
When an expression or statement involves multiple operators, Python resolves the order of execution through
Operator Precedence. The chart of operator precedence from highest to lowest for the operators covered in this
chapter is given below:-
Associatively is the order in which an expression having multiple operators of same precedence is evaluated.
All operators are left-to-right associative except exponentiation (right-to-left associative).
Expressions
An expression in python is any valid combination of operators and atoms. An expression is composed of one or more
operators.
Arithmetic expressions Relational expressions Logical expressions String expressions Compound expressions
For example For example For example For example For example
3+4 a>b a and b “ram” + “mohan” a+b > c+d
a+b b<=c b or c “ram” * 2 a*b > c*d
15
Expression Evaluation
16
Floating Point Literals (with decimal Point)
In python, the floating point numbers have precision of 15 digits (double - precision).
Fractional Form Exponent Form / Scientific Form
When value is too small or too big after decimal point, so we
can also use exponent form style, to show in short form.
For example For example
2.0 Mantissa E Exponent
17.5 12 E 5
-13.0 Here 12 refer to Mantissa Part
- 0.00625 Here E refer to always 10
.3 Here 5 refer to exponent Part (raise part of 10)
7.
Here E = 10
12E5 12E-5 12.3E-5
Or 12 X 105 Or 12 X 10-5 Or 12.3 X 10-5
Or 12 X 100000 Or 12 X (1/100000) Or 12.3 X (1/100000)
Or 1200000 Or .00012 Or .000123
Bitwise Operators
It is similar to logical operators but it works with only binary digits zeros and one.
We must convert decimal values in binary digits first.
It is used to change individual bits in an operand.
& | ^ ~
Bitwise and Bitwise or Bitwise xor Bitwise complement
Op1 Op2 & Op1 Op2 | Op1 Op2 ^ Op1 ~
1 1 1 1 1 1 1 1 0 1 0
0 0 0 0 0 0 0 0 0 0 1
1 0 0 1 0 1 1 0 1
0 1 0 0 1 1 0 1 1
Same always zero Reverse the bit
Different always one
For example For example For example For example
4-> 100 4-> 100 4-> 100 4-> 100
5-> 101 5-> 101 5-> 101
100 100 100 ~100
&101 | 101 ^ 101 011
100 101 001
4-> 100 5-> 101 1-> 001 3-> 0 1 1
17
Type Casting
To change one data type to another data type is called type casting.
Implicit Explicit
(Automatic Conversion) (User defined Conversion)
An Implicit type conversion is a conversion The explicit conversion of an operand to a specific
performed by the compiler without programmer’s type is called type casting.
intervention. It is done using type conversion functions that is
In this conversion, all operands are converted up to used as
type of the largest operand, which is called type Syntax:-
promotion. <type conversion function> (<expression>)
Floating point type to integer type conversion results For example
in loss of fractional part. int(), float(), complex(), str()
The python data objects can be broadly categorized into two – mutable and immutable types.
In simple words changeable or modifiable and non-modifiable types.
Integers Lists
Floating point numbers Dictionaries
Complex numbers Sets
Booleans
Strings
Tuples
18
Module
A Python Module is a file which contain some variables and constant, some functions, objects etc. defined in it,
which can be used in other python programs by importing it.
In order to work with functions of math module, we need to first import it to our program by giving statement as
follows as the top line of our python script. For example:-
import math
Python Functions:
import math import math import statistics import random
math.sqrt() math.ceil() statistics.mean(value) random.random()
math.fabs() math.floor() statistics.median(value)) random.randint( start, stop)
math.pow() statistics.mode(value)) random.randrange( start, stop, step)
random-> to display any random value.
# to display pi value #to find largest value. #to find average value of list #to display a value from 0.0 to 1.0
value=[1,2,3,3]
print( math.pi ) print(math.ceil( 1.10)) print(statistics.mean(value)) print(random.random())
output:- 3.141592653589793 output:- 2 output:- 2.25 output:- 0.8
# to display e value #to find largest value. #to find middle value of list #to display a value from 1 to 10
value=[1,2,3,3]
print( math.e ) print(math.ceil( -1.10)) print(statistics.median(value)) print(random.randint(1, 10))
output:- 2.718281828459045 output:- 1 output:- 2.5 output:- 4
#to find square root of any value #to find smallest value. #to find highest frequency value of list #to display a value from 91 to 100
value = [1, 2, 3, 3]
print(math.sqrt(144)) print(math.floor( 1.10)) print(statistics.mode(value)) print(random.randint( 91, 100))
output:- 12.0 output:- 1 output:- 3 output:- 95
#to find absolute value (only #to find smallest value. #to display a value from 0 to 45
+ve value return).
print(random.randrange( 45 ))
print(math.fabs(-1.10)) print(math.floor( -1.10)) output:- 12
output:- 1.10 output:- -2
#to display a value from 11 to 45
3
#to find power of any value 2 #to display a value from 11 to 45 but
in 4 steps gap
print(math.pow(2, 3)) print(random.randrange(11, 45, 4))
output:- 8.0 output:- 15
19
General Maths Expression Python Programming Expression Similar
XY X*Y
X(Y+Z) X*(Y+Z)
23 2 * 2 *2
or
2 ** 3
or
math.pow(2, 3)
X=2 X=2
Y = X3
Y=X* X*X
or
Y = X ** 3
or
Y = math.pow(X, 3)
√𝟏𝟒𝟒 math.sqrt(144)
X = 144 X = 144
Y= √𝐗 Y= math.sqrt(X)
𝐀 = 𝛑𝐫 𝟐 import math
A = 3.14 * r * r
or
A = 3.14 * r ** 2
or
A = math.pi * r * r
or
A = math.pi * math.pow(r, 2)
2𝛑r 2 * 3.14 * r
Or
2* math.pi * r
X2 + Y 2 (X * X) + (Y * Y)
or
(X ** 2) + (Y ** 2)
or
math.pow(X, 2) + math.pow(X, 2)
X2 + Y 3 (X * X) + (Y * Y* Y)
or
(X ** 2) + (Y ** 3)
or
math.pow(X, 2) + math.pow(X, 3)
X2 / Y 3 (X * X) / (Y * Y* Y)
or
(X ** 2) / (Y ** 3)
or
math.pow(X, 2) / math.pow(X, 3)
20
√𝐛 𝟐 − 𝟒𝐚𝐜 x= math.sqrt(b*b – 4 * a *c) / 2 * a
𝐱=
𝟐𝐚
P = 2 – ye2y + 4y p = 2 – y * math.exp(2*y) + 4 * y
𝑞
p =𝑝+ P = p + q / math.pow ((r + s) , 4)
r+s 4
21
+ (Plus) Operator
+ + + + + +
Addition of values Concatenation (joining) Concatenation of Concatenation of Type casting- Type casting-
of strings from string data type to from integer data type
strings strings integer data type to string data type
a=2 a="2" a='2' a=”ram” a =int('2') a=str(2)
b=3 b="3" b='3' b=”mehta” b =int('3') b=str(3)
c=a+b c=a+b c=a+b c=a+b c=a+b c=a+b
print(c) print(c) print(c) print(c) print(c) print(c)
Output:- 5 Output:- 23 Output:- 23 Output:- rammehta Output:- 5 Output:- 23
Here c hold integer value Here c hold string Here c hold string Here c hold string Here c hold integer value Here c hold string
Explanation:- Explanation:- Explanation:- Explanation:- Explanation:- Explanation:-
Inside memory:- Inside memory:- Inside memory:- Inside memory:- Inside memory:- Inside memory:-
Integer converts into String
a=2 a = “2” a = ‘2’ a=”ram” String converts into integer
a=2 a = “2”
b=3 b = “3” b = ‘3’ b=”mehta”
b=3 b = “3”
c = 2 +3 c = “2” +”3” c = ‘2’ + ’3’ c=”ram”+”mehta”
so it will sum above values so it will join above strings so it will join above strings so it will join above strings c = 2 +3 c = “2” +”3”
so it will join above strings
5 “23” ‘23’ “rammehta” so it will sum above values
5 “23”
* (Multiplication) Operator
** (Exponent) Operator
* (String Replicate) Operator
* ** ** * * *
Multiplication of Exponent Operator Exponent Operator String replicate Operator String replicate Operator String replicate Operator
values Base**Exponent Base**Exponent string*integer integer*string string*integer
a=2 a=2 a=2 a=”ram” a=”ram” a=”ram”
b=3 b=3 b=3 b=3 b=3 b=2
c=a*b c=a**b c=b**a c=a*b c=b*a c=a*b
print(c) print(c) print(c) print(c) print(c) print(c)
Output:- 6 Output:- 8 Output:- 9 Output:- ramramram Output:- ramramram Output:- ramram
Here c hold number Here c hold number Here c hold number Here c hold string Here c hold string Here c hold string
Explanation:- Explanation:- Explanation:- Explanation:- Explanation:- Explanation:-
2*3 23 32 Here * is not perform Here * is not perform
multiplication but
Here * is not perform
multiplication but multiplication but
replication (duplication)
replication (duplication) of replication of same
of same strings 3 times.
Here 2 is base Here 3 is base same strings 3 times. strings 2 times.
Here 3 is exponent Here 2 is exponent One important thing it is
One important thing it is an exception case
an exception case because because here datatype
here datatype mismatch mismatch error will not
error will not occur. occur.
Errors and Solution
Expression Output: Explanation Remove errors
2+ 3 5 Sum of two integers
‘2’ + ‘3’ ‘23’ Concatenation(joining) of two strings
2*3 6 Multiplication of two integers
“2” * 3 “222” Replication(Duplication) of “2” string three times
3 * “2” “222” Replication(Duplication) of “2” string three times
‘2’ + 3 Error Type error: cannot concatenate ‘str’ and ‘int’ objects Two possibilities of solutions
(data type conversion)
FIRST int(‘2’) + 3
2+3 = 5
SECOND ‘2’ + str(3)
‘2’ + ‘3’
‘23’
“2” * “3” Error Type error: can’t multiply sequence by non-int of type ‘str’ One solution
(data type conversion:-
string to integer)
22
ASCII (American Standard Code for information Interchange)
It is a 7 – bit code and enough to represent all of the standard keyboard characters (Almost 128) in the computer
memory as well as control functions such as the (Return) and (LineFeed). But some important ASCII Code ranges
keep in mind:-
chr( ) ord( )
It returns ASCII character of a number. It returns ASCII number of a character.
For example For example
x= 65 x= ‘A’
print(x) print(x)
print(chr(x)) print(ord(x))
output:- output:-
65 A
A 65
For example For example
x= 65 x= ‘A’
y = 66 y = ‘B’
z = x+ y z = x+ y
m = chr(x)+ chr(y) m = ord(x)+ ord(y)
print(z) print(z)
print(m) print(m)
output:- output:-
131 AB
AB 131
Explanation:- Explanation:-
Inside memory Inside memory
x= 65 x= ‘A’
y = 66 y = ‘B’
z = 65+ 66 (so sum is 131) z = ‘A’ + ‘B’ (so it will join ‘AB’)
m = ‘A’+ ‘B’ (so it will join ‘AB’) m = 65 + 66 (so sum is 131)
23
Divide Operation in python
/ // %
Divide Operator Floor Division Modulus operator
Give quotient including decimal Give quotient only integer part Give remainder in integer part or decimal part
part also. also.
5/2 = 2.5 5//2 = 2 5%2 = 1
Expression Evaluation
5/2*3 5*2/ 3
7.5 3.3333333333333335
Explanation Explanation
5/2*3 5*2/ 3
5/2*3 5*2/ 3
2.5 * 3 10 / 3
7.5 3.3333333333333335
In above example following operator in same level but evaluation direction always left to right. So first any
following operator will meet so it will evaluate first in left to right direction.
*, /, // , % Multiplication, division, floor division, remainder Left to Right
Expression Evaluation
5/2*3+2-1 5*2/ 3–2+1
8.5 2.3333333333333335
Explanation Explanation
5/2*3+2-1 5*2/3-2+1
5/2*3+2-1 5*2/3-2+1
2.5 * 3 + 2 - 1 10 / 3 - 2 + 1
7.5 + 2 - 1 3.3333 - 2 + 1
9.5 - 1 1.3333 + 1
8.5 2.3333333333333335
In above example following operator (*, /, // , %) in same level but evaluation direction always left to right. So first
any following operator will meet so it will evaluate first in left to right direction.
After evaluating all (*, /, // , %) this operators then (+, -) operators will evaluate in left to right direction.
*, /, // , % Multiplication, division, floor division, remainder Left to Right
+, - Addition, subtraction Left to Right
24
For example:-
5+2*3-2/1
9.0
Explanation Explanation
5+2*3-2/1
5+2*3-2/1 First left to right first * operator evaluate
5+6-2/1 Then left to right / operator evaluate
5 + 6 – 2.0 Then left to right + operator evaluate
11 – 2.0 Then left to right - operator evaluate
9.0 Final result
For example:-
5-2/3*2+1
4.666666666666667
Explanation Explanation
5-2/3*2+1
5-2/3*2+1 First left to right first / operator evaluate, it give float value
5 – 0.66 * 2 + 1 Then left to right * operator evaluate
5 – 1.33 + 1 Then left to right - operator evaluate
3.66 + 1 Then left to right + operator evaluate
4.666666666666667 Final result
For example:-
5 - 2 // 3 * 2 + 1
6
Explanation Explanation
5 - 2 // 3 * 2 + 1
5 - 2 // 3 * 2 + 1 First left to right first // operator evaluate, it give integer value
5–0 *2+1 Then left to right * operator evaluate
5–0+1 Then left to right - operator evaluate
5+1 Then left to right + operator evaluate
6 Final result
25
For example:-
5-2%3*2+1
2
Explanation Explanation
5-2%3*2+1
5-2%3*2+1 First left to right first % operator evaluate, it give remainder value
5–2 *2+1 Then left to right * operator evaluate
5–4+1 Then left to right - operator evaluate
1+1 Then left to right + operator evaluate
2 Final result
For example:-
5 - 2 % (3 * 2) + 1
4
Explanation Explanation
5 - 2 % (3 * 2) + 1
5 - 2 % (3 * 2) + 1 First left to right first ( ) evaluate, it give multiplication value
5–2 %6+1 Then left to right % operator evaluate, it give remainder value
5–2+1 Then left to right - operator evaluate
3+1 Then left to right + operator evaluate
4 Final result
For example:-
2>5 and 7>5 2>5 or 7>5 1+2>5+3 and 6+7>5-7 1+2>5+3 or 6+7>5-7
False and True False or True 3>8 and 13>2 3>8 or 13>2
False True False and True False or True
False True
Note: - First evaluate arithmetic Note: - First evaluate arithmetic
expression, and then evaluate expression, and then evaluate
relational expression and finally relational expression and finally
logical expression. logical expression.
26
Strings and size
len( )- It is used to count total number of characters in a given string including white spaces also.
But len function does not count escape characters (\) in a given string.
Single Line String Multiline String
Must use \ symbol for next line
str='ab' str='python language' str= 'a\ str='python\
b' language'
= ==
Assignment Operator Equality operator
It is used to assign/store a value to a variable. It is used to compare two values.
For example For example
x = 10 x = 10
y = 20 y = 20
z = 30 z = (x == y)
print(z) print(z)
output:- output:-
30 False
Python Drawbacks:-
1. Not the Fastest language:- Python is an interpreted language and not a compiled language.
2. Lesser Libraries than C, Java, Perl
3. Not strong on Type-binding
4. Not Easily Convertible
27
Debugging
The process of identifying and removing logical errors and runtime errors is called debugging.
Due to errors, a program may not execute or may generate wrong output. So three types of errors
Here highlighted line will give syntax Here syntax of highlighted line is Here syntax of highlighted line is
error because we cannot use variable correct. But you want to perform correct and also you want to perform
in Right side. multiplication operation not addition divide operation but by mistake, if
operation. So for this you must use the denominator value is zero then it
operator * instead of + will give a runtime error like “division
by zero”.
28
Scientific Form of Real Constants
When value is too small or too big after decimal point, so we can also use exponent form style, to show in short
form.
Here, E (Exponent) always refer 10
In Mathematics X0 = 1
so 100 = 1
29
Representing Characters in Memory
American Standard Code for information interchange Indian Standard Code for information interchange Universal Code
Mainly focus on keyboard letters. Devanagari, Gurmukhi, Gujarati, Oriya, It includes ASCII, ISCII letters also but Korean,
English, Numbers and other special Bengali, Assamese, Telugu, Kanada, Japanese, Chinese characters and other world
7-bits use to store a character. 8-bits (1 byte) use to store a character. 16 –bits (2 bytes)
7 16
2 = 128 characters maximum store. 28 = 256 characters maximum store. 2 = 65536 characters maximum store.
For Example:-
Valid Integer literal Invalid Integer literal with reasons Valid Float literal Invalid Float literal with reasons
41 41.5 (decimal point not allowed) 17.5 +17/2 (/- illegal symbol)
+97 Ninety Seven (words form not allowed) -13.0 17,250.26.2 (Two decimal points)
‘hello’ ‘hello”
“hello” “hello’
‘’’hello’’’ {hello}
30
String Indexing and Slicing Operation
31
Membership Operators in String
in not in
Return True if a characters or a substring exists in the Return True if a characters or a substring does not exists
given string; False otherwise in the given string; False otherwise
Syntax: Syntax:-
<string> in <string> <string> not in <string>
Code Output Code Output
“p” in “python” True “p” not in “python” False
“P” in “python” False “P” not in “python” True
“py” in “python” True “py” not in “python” False
“th” in “python” True “th” not in “python” False
“on” in “python” True “on” not in “python” False
“yth” in “python” True “yth” not in “python” False
“ythm” in “python” False “ythm” not in “python” True
“ab” == “ab” “ab” != “ab” “b” > “a” “b” < “a” “b” >= “a” “b” <= “a”
True False False
True False True
“A” == “a” “A” != “a” “a” >= “a” “a” <= “a”
False True True True
“b” >= “b” “b” <= “b”
True True
32
To display ASCII Value of a character. To display ASCII Character of a number.
ord(<character>) chr(<int>)
It returns ASCII values. It returns ASCII Characters.
Code Output Code Output
ord(‘A’) 65 chr(65) ‘A’
ord(‘B’) 66 chr(66) ‘B’
ord(‘C’) 67 chr(67) ‘C’
ord(‘a’) 97 chr(97) ‘a’
ord(‘b’) 98 chr(98) ‘b’
ord(‘c’) 99 chr(99) ‘c’
* **
Multiplication Operator Exponent Operator
(Always Left to Right Direction Evaluate) (Always Right to Left Direction Evaluate)
For Example For Example
x = 1*2*3 x = 1**2**3
x = 2*3 * -> Left to Right Evaluate x = 1**8 * -> Right to Left Evaluate
(18 = 1*1*1*1*1*1*1*1)
x=6 x=1
33
Computer Number Conversion
1 0 1 1 1 1 1 1 3 7 5 F
Step1 6 5 4 3 2 1 0 Step1 2 1 0 Step1 5 15
Step2 26 25 24 23 22 21 20 Step2 8 2
8 1
80 Step2 1 0
1
Step3 64 32 16 8 4 2 1 Step3 64 8 1 Step3 16 160
Step4 1*64 0*32 1*16 1*8 1*4 1*2 1*1 Step4 1*64 3*8 7*1 Step4 16 1
Step5 64 0 16 8 4 2 1 Step5 64 24 7 Step5 16*5 1*15
64+0+16+8+4+2+1 64+24+7 Step6 80 15
95 95 80+15
( 95 )10 ( 95 )10 95
( 95 )10
34
Python Programs
1. Write a python program to input 2. Write a python program to input 3. Write a python program to input two
two values and display sum. two values and display Subtraction. values and display Multiplication.
4. Write a python program to input 5. Write a python program to input 6. Write a python program to input
two values and display division. length and width of a rectangle and base and height of a triangle and
display area of rectangle. display area of triangle.
Solution:- Solution:- Solution:-
a = int(input(“Enter First Value”)) l = int(input(“Enter length Value”)) b = int(input(“Enter base Value”))
b = int(input(“Enter Second Value”)) w = int(input(“Enter width Value”)) h = int(input(“Enter height Value”))
c=a/b a=l*w a = (b * h)/2
print(“division is”, c) print(“Area is”, a) print(“Area is”, a)
output:- output:- output:-
Enter First Value 4 Enter length Value 4 Enter base Value 4
Enter Second Value 2 Enter width Value 2 Enter height Value 2
division is 2 Area is 8 Area is 4
7. Write a python program to input 8. Write a python program to input 9. Write a python program to input
radius of a circle and display area of radius of a circle and display side of a square and display area of
circle. Perimeter of circle. square.
Solution:- Solution:- Solution:-
r = int(input(“Enter radius Value”)) r = int(input(“Enter radius Value”)) s = int(input(“Enter side value”))
a = 3.14 * r * r a = 2* 3.14 * r a=s*s
print(“Area is”, a) print(“Perimeter is”, a) print(“Area is”, a)
output:- output:- output:-
Enter radius Value 2 Enter radius Value 3 Enter side Value 3
Area is 12.14 Perimeter is 18.14 Area is 9
35
10. Write a python program to input What will be the output:- Which of the following are invalid
marks of three subjects and #This is a simple program strings in Python?
calculate total and percentage and #to output simple statements (a) “Hello”
also display total and percentage #print(“such as”) (b) ‘Hello’
value. print(“Take every chance.”) (c) “Hello’
print(“Drop every fear.”) (d) ‘Hello”
(e) { Hello}
Solution:- Ans. Ans.
eng = int(input(“Enter English Marks”)) Take every chance. (c) because one “ and other ‘ is not allowed
math = int(input(“Enter Maths Marks”))
Drop every fear. (d) because one ‘ and other “ is not allowed
science= int(input(“Enter Science Marks”))
(e) because { } is not allowed
total = eng + math + science
#print(“such as”) will not display because # symbol
percentage = (total * 100) / 300
will make this a comment and comment will not
print(“Total is”, total)
execute.
print(“Percentage is”, percentage)
output:-
Enter English Marks 50
Enter Maths Marks 70
Enter Science Marks 40
Total is 160
Percentage is 53.33
What will be the sizes of following:- Identify the types: What is None literal in python?
(a) ‘\a’ 23.789
(b) “\a” 23789
(c) “Reema\’s” True
(d) ‘\”’ ‘True’
(e) “it’s” “True”
(f) “xy\ False
yz” “False”
Ans. 23.789 -> Float Value Ans. The None literal is used to
23789 -> Integer
(a) 1 indicate something that has not yet
(b) 1 True -> Boolean
been created in simple words, or
(c) 7 ‘True’ -> String
(d) 1 “True” -> String absence of value. It is also to indicate
(e) 4
False ->Boolean the end of lists in python.
(f) 4 it is a multi line string.
“False” ->String
Note only \ is not count.
36
What will be output produced by What will be the output of following What will be the output of following
following code? code? code?
value = ‘simar’ x, y = 2, 6 x, y = 2, 6
age = 17 x, y = y, x + 2 x =y
print(x, y) y= x+2
print (name, “,you are”, 17, “now but”, end=’ ‘) print(x, y)
print (“you will be”, age + 1, “next year”)
output:-
6, 4 output:-
output:-
Simar, you are 17 now but you will be 18 next year.
6, 8
Inside following thing will happen
x, y = 6, 2 + 2 Inside following thing will happen
x is 6 x, y = 2, 6
y is 4 x =6
y= 6+2
Here first RHS part will execute first Here last value of x used.
completely and then assign values. Here line by line code will execute
Predict the output of following:- Select valid and invalid identifiers:- What will be the output produced by
x, y = 7, 2 (a) profit these?
x, y, x = x +1, y +3, x + 10 (b) loss (a) 12 / 4
print(x, y) (c) 2code (b) 14 / 14
(d) code2 (c) 14 % 4
output:- (e) file_name (d) 14.0 / 4
17 5 (f) file.name (e) 14.0 // 4
(g) roll no (f) 14.0 % 4
Inside following thing will happen
x, y, x = 7+1, 2+3, 7+10 Ans. Ans.
x, y, x = 8, 5, 17 Valid (a), (b), (d), (e) (a) 3.0 it return quotient.
x is 17 (b) 1 it return quotient.
y is 5 Invalid (c), (f), (g) (c) 2 it return remainder
(c) first letter must be alphabet. (d) 3.5 it return decimal part also.
(f) . (dot) is not allowed (e) 3.0 it return integer part
(g) space is not allowed. (f) 2.0 it return remainder
37