Computer Science Notes 11th_02
Computer Science Notes 11th_02
CHAPTER PAGE
CHAPTER NAME
NO. NO.
1 INTRODUCTION TO PYTHON 2
2 PYTHON FUNDAMENTALS 5
3 DATA HANDLING 16
4 FLOW OF CONTROL 27
5 FUNCTIONS IN PYTHON 38
6 STRING IN PYTHON 50
7 LIST IN PYTHON 61
8 TUPLE IN PYTHON 75
9 DICTIONARY IN PYTHON 85
10 SORTING 95
11 DEBUGGING PROGRAMS 99
Praveen kumar A
Page 1
CHAPTER-1
INTRODUTION TO PYTHON
1.1 Introduction:
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol-
68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Page 2
Praveen kumar A
i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
Output: 9
Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\program1.py”).read( ))
ii. Script Mode: In this mode source code is stored in a file with the .py extension
and use the interpreter to execute the contents of the file. To execute the script by the
interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name Demo.py , to run the script you have to follow the following
steps:
Page 4
CHAPTER-2
PYTHON FUNDAMENTALS
2.2 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators
as elif if or yield
All the keywords are in lowercase except 03 keywords (True, False, None).
Page 5
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.
3. Literal: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.
Literal
String Literal
Numeric Boolean Special
Collections
Eg.
5, 6.7, 6+9j
Page 6
B. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.
Eg:
"Aman" , '12345'
C. Boolean literal: A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
4. Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator
5. Separator or punctuator : , ; , ( ), { }, [ ]
Page 8
2.4 Basic terms of a Python Programs:
A. Blocks and Indentation
B. Statements
C. Expressions
D. Comments
B. Statements
A line which has the instructions or expressions.
C. Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.
D. Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.
Page 9
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment
i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Page 10
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)
Creating a variable:
Example:
x=5
y = “hello”
Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print(x)
Example: x=y=z=5
You can also assign multiple values to multiple variables. For example −
x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12
Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.
If you want to know the type of variable, you can use type( ) function :
Page 12
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x
del y, z
Page 13
int( ) - constructs an integer number from an integer literal, a float literal or a string
literal.
Example:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example:
Page 14
object : It can be one or multiple objects separated by comma.
sep : sep argument specifies the separator character or string. It separate the objects/items. By
default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30
Data Types
Primitive Collection
Data Type Data Type
Number String
int
float
complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
Page 16
integer : There are two types of integers in python:
int
Boolean
x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:
>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
float : float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100
Page 17
complex : Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>z.real
5.0
>>>z.imag
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
Page 18
3.2 MUTABLE & IMMUTABLE Data Type:
Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple.
RESULT
OPERATOR NAME SYNTAX
(X=14, Y=4)
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
// Division (floor) x // y 3
% Modulus x%y 2
Page 19
Example:
>>>x= -5
>>>x**2
>>> -25
RESULT
OPERATOR NAME SYNTAX
(IF X=16, Y=42)
False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y
iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
Page 20
a. Relational expressions as operands:
X Y X and Y
False False False
False True False
True False False
True True True
X Y X or Y
False False False
False True True
True False True
True True True
X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand
True # is false, otherwise ignores it, even if the second operand is wrong
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
| Bitwise OR x|y
Page 22
~ Bitwise NOT ~x
Examples:
Let Output:
a = 10 0
b=4
14
print(a & b) -11
print(a | b) 14
2
print(~a)
40
print(a ^ b)
print(a >> 2)
print(a << 2)
v. Assignment operators: Assignment operators are used to assign values to the variables.
OPERA
TOR DESCRIPTION SYNTAX
a. Identity operators- is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]
Page 24
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)
Output:
False
True
False
Example:
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False
b. Membership operators- in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}
print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)
Page 25
Output:
True
True
False
True
False
Page 26
CHAPTER-4
FLOW OF CONTROL
2. Looping or Iteration
3. Jumping statements
Page 27
There are three types of conditions in python:
1. if statement
2. if-else statement
3. elif statement
2. if-else statement: When the condition is true, then code associated with if statement will
execute, otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3. elif statement: It is short form of else-if statement. If the previous conditions were not true,
then do this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
Page 28
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
while
Loops in loop
Python
for loop
Page 29
1. while loop: With the while loop we can execute a set of statements as long as a condition is
true. It requires to define an indexing variable.
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2
2. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)
it generates a list of numbers, which is generally used to iterate over with for loop.
range( ) function uses three types of parameters, which are:
a. range(stop)
b. range(start, stop)
Note:
Page 30
a. range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,
but not including stop value.
Example:
for x in range(4):
print(x)
Output:
0
1
2
3
b. range(start, stop): It starts from the start value and up to stop, but not including
stop value.
Example:
Output:
2
3
4
5
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.
Example:
print(x)
Output:
3
5
7
Page 31
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and
increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 value
that is 8 here. So, the output is 3, 5, 8.
S.
No. range( ) xrange( )
1. break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i = 1 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
print(i) if x == "python":
if i == 3: break
break print(x)
i += 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
Page 32
2. continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i = 0 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
i += 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)
Output: Output:
1 java
2 c++
4
5
6
Syntax:
for loop while loop
Page 33
Syntax:
for <variable-name> in <sequence>:
for <variable-name> in <sequence>:
statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
Page 34
3. Write a program to check a year whether it is leap year or not.
year=int(input("Enter the year: "))
if year%100==0 and year%400==0:
print("It is a leap year")
elif year%4==0:
print("It is a leap year")
else:
print("It is not leap year")
Page 35
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
Page 36
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")
Page 37