You are on page 1of 15

M.E.

S INDIAN SCHOOL (MESIS)


ABU HAMOUR BRANCH, DOHA – QATAR
NOTES [2024-2025]
Class & Div. : XII B Subject : Computer Science
Lesson / Topic : 1. Python Revision Tour I Date : 17/03/2024
=====================================================================================================

Ref. No: CS-N-01

Keywords :

 Keywords are the words that have special meaning reserved by programming language.
 They are reserved for special purpose and cannot be used for normal identifier names.
 E.g. in, if, break, class, and, continue, True, False

Identifiers :

 Identifiers are fundamental building block of a program.


 They are names given to variable, functions, objects, classes, etc.
 Python is case sensitive i.e. it treats upper case and lower case letter differently.
 Naming Conventions:
• Contain A-Z, a-z, _
• Name should not start with digit
• It can start with alphabet or ( _ ) underscore

Literals :

 Literals are data items that have fixed value.


 Python allows several kinds of literals:
• String literals
• Numeric literals
• Boolean literals
• Special Literal None
• Literal Collections

String Literals

 The text enclosed in single or double quotes.


 There is no character literal.
 Example ‘a’, ‘anant’, “HelloWorld”
 Python allows non-graphic characters in string values.
 Non-graphic characters are represented using escape sequence.
\n for newline, \t for tab space, \r for carriage return

ACD-105, REV 0, 27.03.2021


String Types in Python :

 Strings are declared in two ways :


Single - line String : enclosed within single or double quotes. It must terminate in one line.
Eg : Text1 = “Computer”
Text2 = ‘Science’
 Multiline String : text spread over multiple lines in one single string.
• It can be created in two ways
• By adding backslash at end of each line
• By enclosing the text in triple quotation mark
Eg : text1 = “Welcome\
to\
MESIS”
print(text1)
Welcome to MESIS

text2 = ‘ ’ ’Welcome
to
MESIS’ ’ ’
print(text2)
Welcome
to
MESIS

Size of Strings :

 Size of string can be determined by len( ) function.


 It tells the count of the characters in the string.
 In multiline comments backslash is not counted.
 In multiline comments with triple quotes EOL character at end of line is counted.
 Eg :
text3 = “Computer”
text4 = “Computer\
Science”
text5 = ‘ ’ ’Computer
Science’ ‘ ‘
text6 = “CS\a”
print(len(text3))
print(len(text4))
print(len(text5))
print(len(text6))

8
15
17
3

ACD-105, REV 0, 27.03.2021


Numeric Literals :

 Integer : positive negative numbers without decimal


 Floating Point : Real numbers with decimal points
 Complex Number : are in form a + bj, where a and b are floating point numbers and j is √-1.
where ‘a’ is real part and ‘b’ is imaginary part.

Boolean literals Special Literal None :

 ‘True’ and ‘False’ are the two Boolean Literals.


 Special literal ‘None’ represent absence of value.
 ‘None’ also indicates end of List.
 They are built-in constant literals of Python.

Operator :

Operators are the symbol, which triggers some computation when applied on operand.
 Unary Operator : those operators that require only one operand.
 Unary Plus +
 Unary Minus –
 Bitwise Complement ~
 Logical Negation not
 Binary Operator : those operators that require only two operand.
 Arithmetic Operator +, -, *, /, %
 Bitwise Operator &, ^, |
 Shift Operator >> , <<
 Identity Operator is , is not
 Relational Operators
 Less Than <
 Greater Than >
 Less Than or Equal to <=
 Greater than or Equal to >=
 Equal To ==
 Not Equal to !=
Eg :
a=3>6
print (a)
b = 13 < 60
print (b)
d = 3 == 6
print (d)

False
True
False
 Logical Operators
 Logical AND and
 Logical OR or
ACD-105, REV 0, 27.03.2021
Eg :
a = 3 > 6 and 13 < 60
print (a)
a = 3 > 6 or 13 < 60
print(a)
False
True
 Assignment Operator
 Assignment =
 Assign Quotient /=
 Assign Sum +=
 Assign Product *=
 Assign Remainder %=
 Assign Difference -=
 Assign Exponent **=
 Assign Floor Division //=
Eg :
n = 10
n/=2
print(n)
n+=5
print(n)
n*=2
print(n)
n%=3
print(n)
n//=2
print(n)
5.0
10.0
20.0
2.0
1.0
 Membership Operator
 Whether variable in sequence in
 Whether variable not in sequence not in
Eg :
sub = ‘a’ in ‘ram’
print(sub)
sub = ‘a’ not in ‘ram’
print (sub)
sub = ‘t’ in ‘ram’
print(sub)
sub = ‘t’ not in ‘ram’
print(sub)

ACD-105, REV 0, 27.03.2021


True
False
False
True

Punctuator :

• Punctuators are the symbols used in programming language to organise the statements of the
program.
• Common Punctuators are ‘ “ # \ ( ) [ ] { } @ , : . =

Barebones of Python Program :

Components of Program are


 Expression: legal combination of symbols to represent a value.
Eg : A=5 b=b+9
 Statement: Instruction that performs certain action.
Eg : Print(“Hello”) if(a>90):
 Comments: Additional information regarding the source code which is not executed.
 Single Line Comment : begins with ‘#’
 Multiline Comments : enclosed in triple quotes (‘’’) called doc string
 Functions : block of code having name , and can be reused by specifying the name in the
program, whenever required.
 Block and Indentation: Group of statement which are part of another statement or function.

Variable and Assignments :

 Named Label whose value can be changed and processed during the program run.
Creating Variable :
name = ‘Anant’
age = 9
age = 30
 Python do not have fixed memory locations, when the value changes they change their
location.
 Lvalue : expression that can come on left hand side of an assignment.
 Rvalue : expression that can come on right hand side of an assignment.

Dynamic Typing :

The process in which the variable pointing to a value of certain type, can be made to point to
the value of other type.
Eg :
age = 10
print(age)
age = “ten”
print(age)

ACD-105, REV 0, 27.03.2021


note : Keep the data type in mind while changing.
• type( ) function is used to determine the type of object.

Eg :
name = ‘anant’
print(name)
name = 60
print(name)

anant
60

Dynamic Typing vs Static Type :

 In Dynamic Typing the datatype attached with the variable can change during the program run
where as in Static Typing the data type defined for the first time is fixed for the variable.
 Python Support Dynamic Typing.
Multiple Assignment :

 Python allows Multiple assignments.


 Assign same value to multiple variables.
Eg :
x = y = z = 20
here x, y, z has same value 20
 Assign multiple values to multiple variables.
Eg :
x , y , z = 20, 40, 60
here x, y, z has value 20, 40 and 60 respectively

Variable Definition :

 Variable is created or defined when the first value is assigned to it.


 Variable is not created until some value is assigned to it.

Simple Input and Output :

 input( ) function is used for taking value for a variable during runtime.
Eg :
name = input(“Enter your name : “)
print(“Name : “, name)

Enter your name : Ayaan


Name : Ayaan

ACD-105, REV 0, 27.03.2021


Reading Numbers :

 To overcome the above error we need to convert the string type object to integer or any
desired numeric type.
 input( ) function always returns a value of string type.
 Use int( ) or float( ) function to convert the type string to int and float respectively.
Eg :
age = int(input(“Enter your age : “)
age1 = age + 10
print(“Age after 10 years”, age1)
Enter your age : 20
Age after 10 years 30

Possible Errors while Reading Numeric Values :


 When converting variable to int / float we need to make sure that the value entered is of int /
float type.
Eg :
age = int(input(“Enter your age : “)
age1 = age + 10
print(“Age after 10 years : “, age1)

Enter your age : fatima


 If we enter fatima for age then fatima cannot be converted to int.

Output Through print Statement :


 print statement has number of features.
 Automatic conversion of items to string type.
 Inserting space between items automatically as default value of sep (separator) is space.
Eg :
name = input(“Enter your name : “)
print(“My”, “name”, ïs”, name)
Enter your name : Joan
My name is Joan
 It appends a newline at the end of the each print line.
Eg :
print(“My name is Aisha”,)
print(“Age : 18”)

My name is Aisha
Age : 18
 sep and end argument in print statement
Eg :
print(“My”, “name”, “is Amaira”, sep = “$”, end = “…”)
print(“Age : 18”, sep = “$”, end = “…”)
My$name$is Amaira…Age : 18…

ACD-105, REV 0, 27.03.2021


Data Types :
Python offers five built-in core data types
 Numbers( int, float, complex)
 String
 List
 Tuples
 Dictionary
Numbers :
 Integers
 Integers Signed : positive and negative integers (Whole Numbers)
 Boolean: Truth Values False(0)/bool(0) and True(1) /bool(1)
 Floating Point Numbers : precision of 15 digits possible in Python
 Fractional Form : Normal Decimal Form, Eg : 325.89, 300.845
 Exponent Notation : Represents real numbers for measurable quantities.
Eg : 3.500789E05, 1.568789E09, 0.254E-07
 Complex Numbers : Python represents complex numbers as a pair of floating point
numbers. Eg : A+Bj. J is used as the imaginary part which has value √-1.
 a = 1.6 + 4j real part = 1.6 imaginary component = 4
 b = 0 + 5.2j real part = 0 imaginary component = 5.2
 a.real and b.real gives the real part
 a.imag and b.imag gives the imaginary part
Eg : >>> a.real
1.6
String :
 Any number of valid characters within quotation marks.
 It can hold any type of known characters like alphabets, numbers, special characters etc.
 Legal String in Python are “Raman”, ‘rocket’, “we2345@”,”%&$#”
 String as a sequence of Characters
 String is stored as individual characters in contiguous location.
Forward Indexing 0 1 2 3 4 5
P y t h o n
-6 -5 -4 -3 -2 -1 Backward Indexing
 Length of the string can be determined using len(string).
 Individual letter of a string cannot be changed because the String is immutable.
Eg : name = ‘hello’
name*2 += ‘g’ # Not Possible
name = ‘Computer’ #Possible , we can assign string to another string
List :
 List in Python represents a list of comma-separated values of any data type between square
brackets. Mutable Data Type
Eg : [1,2,3,4,5]
[‘a’, ‘b’,’c’,’d’]
[‘rat’, ‘bat’,’cat’,’dog’]
>>>List = [1,2,3,4,5] >>>print(List) [1,2,3,4,5]
>>>List[0] = 20 >>>print(List) [20,2,3,4,5] #changes the 1st element
>>>List[3] = 8 >>>print(List) [20,2,3,8,5] #changes the 4th element
ACD-105, REV 0, 27.03.2021
Tuples :
 Tuples in Python represents a list of comma-separated values of any data type between round
brackets. Immutable Data Type
Eg : T = (1, 2, 3, 4, 5)
A = (‘a’, ‘b’, ’c’, ’d’)
B = (‘rat’, ‘bat’, ‘cat’, ’dog’)

Dictionary :
 Dictionary in Python represents unordered set of comma-separated key : value pair within { },
with the requirement that within a dictionary, no two keys can be the same.
Eg : A = {‘a’ : 1, ‘b’ : 2, ’c’ : 3, ’d’ : 4}
>>>A[‘b’]
2
>>> A[‘d’]
4
Immutable Types :
 The immutable types are those that can never change their value in place.
 Immutable Data Types are
 Integer
 Floating Point Number
 Boolean
 String
 Tuples
Eg : >>>a = 10 >>>print(a) 10
>>>a = 20 >>>print(a) 20
Note : We see that the above code is changing the value of the variable, values are not
changing in place. Variable names are stored as references to a value-object, each time
you change the value, the variable’s reference memory address changes.

Mutable Types :
 Mutable types are those whose values can be changed in place.
 Mutable Data Types are
 List
 Dictionary
 Sets
 Thus Mutability means that in the same memory address, new value can be stored as and when
you want.

Expression :
 Expression is the valid combination of operators, literals and variables.
 Expression is formed by atoms and operators.
 Atoms are something which has value.
Eg : Literals, identifier, string, list, tuples, sets and dictionary etc.
 Types of Expression
 Arithmetic Expression : a + 5 – 6
 Relational Expression : x > 90
 Logical Expression : a > b or 6 < p
 String Expression : “computer” + “science”, “web” *3
ACD-105, REV 0, 27.03.2021
Evaluating Arithmetic Expression :
 During evaluation if the operand are of same data type then the resultant will be of the data
type which is common.
 In case, during evaluation if the operand are of different data type then the resultant will be of
the data type of the largest operand. We need to promote all the operand to the largest type
through type promotion.
 Implicit Type Conversion / Coercion
 Implicit conversion is performed by the compiler without programmer’s intervention.
Eg :
>>>2 + 4.0 #note that the type coercion is done automatically
6.0
>>>2 + 4.0
6.0
>>>1 + 2j + 1
(2 + 2j)

 Note :
Division operator will result in floating point number, even if both operands are integer type.
Eg :
a = 10
b=2
i = a/2
print(i)
5.0

Type Casting :
 Python internally changes the data type of some operand, so that all operand have same data
type. This is called Implicit Type Conversion.
 Explicit Type Conversion / Type Casting : user defined conversion that forces an expression to
be of specific type.
 Type casting is done by <datatype> (expression)
Eg : amt = int(amount)
 Different data types are int(), float(), complex(), str(), bool()
Types of statements in Python

 Smallest executable unit of the program.


 These are instructions given to the computer to perform any kind of action, data movement,
decision making, repeating actions etc.
 They are of three types of statements in Python. They are :
 Empty Statement : Statement which does nothing. In Python empty statement is a pass
statement.
 Simple Statement : Any single executable statement is a simple statement.
 Compound Statement : Group of Statement executed as a unit. It has a header line and a
body.
 Header line : It begins with the keyword and ends with a colon.
 Body : consist of one or more Python statements, indented inside header line. All
statement are at same level of indentation.

ACD-105, REV 0, 27.03.2021


Program to find the Eligibility for voting :
# Voting Eligibility
age = int(input("Enter your age : ")) //Simple Statement
pass //Empty Statement
if age > 17 :
print(“Eligible to vote”)
else : Compound Statement
print(“Not Eligible to vote”)

if Statement :
 In Python, if Statement is the simplest of all decision making statements.
 It will run the body of code only when IF statement is true.
 When you want to justify one condition while the other condition is not true, then you use "if
statement".
 Syntax :
if <expression/condition> :
statement block1
 Example :
a = 33
b = 200
if b > a:
print("b is greater than a")
if else Statement :
 The if else statement provides control to check the true block as well as the false block.
 Syntax :
if <expression/condition> :
statement block1
else :
statement block2
 Example :
a = int(input(“Enter any number : “))
if a%2 == 0 :
print(a, " is even")
else :
print(a, “ is odd”)

if..elif..else Statement :

 When we need to construct a chain of if statement(s) then “elif” clause can be used instead of
“else”.
 “elif” clause combines if..else-if..else statements to one if..elif..else.
 “elif” can be considered to be abbreviation of “else if”.
 In an “if” statement there is no limit of “elif” clause that can be used, but an “else” clause if
used should be placed at the end.

ACD-105, REV 0, 27.03.2021


 Syntax :
if <condition-1> :
statements-block 1
elif <condition-2> :
statements-block 2
else :
statements-block n

o In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then


statements-block1 is executed.
o Otherwise the control checks condition-2, if it is true statements-block2 is executed and
even if it fails statements-block n mentioned in else part is executed.
 Eg :
m1 = int (input(“Enter mark in first subject : ”))
m2 = int (input(“Enter mark in second subject : ”))
avg = (m1+m2)/2
if avg >= 80 :
print (“Grade : A”)
elif avg >= 70 and avg <80 :
print (“Grade : B”)
elif avg >= 60 and avg <70 :
print (“Grade : C”)
elif avg >= 50 and avg < 60 :
print (“Grade : D”)
else :
print (“Grade : E”)

Enter mark in first subject : 34


Enter mark in second subject : 78
Grade : D

Repetition / Iteration of Tasks

 There are many situations when we need to repeat certain task or functions some given
number of times or based on certain condition.

Loop :

 Loops can execute a block of code number of times until a certain condition is satisfied. Their
usage is fairly common in programming. Unlike other programming language that have for loop,
while loop, do while, etc.
 To carry out repetitive task python provides following looping / iterative statements :
 Conditional Loop while
 Counting Loop for

ACD-105, REV 0, 27.03.2021


while loop :

 while loop is used to run a block of code until a certain condition is satisfied.
 Syntax :
while <logical expression> :
loop body
 Anatomy of a while Loop
 Initialization
 Test Expression
 The Body of the Loop
 Update Expression
 Example :
n=1
while n < 5 :
print(“Square of “, n, “ is “, n*n)
n += 1
print(“Thank you”)

Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Thank you

for loop :

 for loop is the most comfortable loop.


 It is also an entry check loop.
 The condition is checked in the beginning and the body of the loop(statements-block 1) is
executed if it is only True otherwise the loop is not executed.
 Syntax :
for counter_variable in sequence :
statements-block 1
[else: # optional
block statements-block 2]
 The counter_variable is the control variable.
 The sequence refers to the initial, final and increment value.
 for loop uses the range() function in the sequence to specify the initial, final and
increment values.
 range() generates a list of values starting from start till stop-1.
 Syntax :
range (start,stop,[step])
where, start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
ACD-105, REV 0, 27.03.2021
 Example :
for i in range(2,10,2) :
print (i, end = ' ')
else :
print ("\nEnd of the loop")
2468
End of the loop

Loop Else Statement :

 Both the loops of Python has else clause. The else of a loop executes only when the loop end
normally (i.e. only when the loop is ending because the while loop’s test condition has become
false and for loop has executed the last sequence)
 Note : The else clause of the Python Loop executes when the loop terminates normally, not
when the loop is terminating because of break statements.

Jump Statement :

 You might face a situation in which you need to exit a loop completely when an external
condition is triggered or there may also be a situation when you want to skip a part of the loop
and start next execution.
 Python provides break and continue statements to handle such situations and to have good
control on your loop.
The break Statement :

 The break statement in Python terminates the current loop and resumes execution at the next
statement.

The continue Statement :

 The continue statement in Python returns the control to the beginning of the while loop. The
continue statement rejects all the remaining statements in the current iteration of the loop
and moves the control back to the top of the loop.

Nested Loop :

 A loop placed within another loop is called nested structure.


 One can place a while within another while, for within another for; for within while and while
within for to construct nested loop.

ACD-105, REV 0, 27.03.2021


Eg :
i–1
while (i <= 6) :
for j in range (1, i + 1) :
print(j, end = ‘\t’)
print(end = ‘\n’)
i += 1

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

*********

ACD-105, REV 0, 27.03.2021

You might also like