Python revision and function
Python revision and function
3. Distribution of Marks:
3 Database Management 20 25 20
Total 70 110 70
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
4 Binary File
5 CSV File
6 Data Structure
7 Computer Networks
Multiline comments: Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
Python character set:
A character set is a set of valid characters acceptable by a programming language in
scripting.
Python supports all ASCII / Unicode characters that include:
o Alphabets: All capital (A-Z) and small (a-z) alphabets.
o Digits: All digits from 0-9.
o Alphabets: All capital (A-Z) and small (a-z) alphabets.
o Special Symbols: Python supports all kinds of special symbols - " ' l ; : ! ~ @ # $
%^`&*()_+–={}[]\.
o White Spaces: White spaces like tab space, blank space, newline, and carriage
return.
o Other: All ASCII and UNICODE characters are supported by Python that
constitutes the Python character set.
Python Tokens:
A token is the smallest individual unit in a python program.
All statements and instructions in a program are built with tokens.
Token Types:
o Keywords: Keywords are reserved by python environment and cannot be used
as identifier. There are 35 keywords in python. You may try to use the following
code to get a list of keywords supported in your python version.
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
o Identifier: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language, and it
has some rules and regulations to name an identifier. Here are the rules.
An Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an
underscore( _ ).
It can have digits but cannot start with a digit.
An identifier can’t be a keyword.
My_name, __init__, Seven10 are valid examples.
20dollers, my.var, True are invalid examples.
o Literals: Literals are the values stored in program memory and are often referred
to by an identifier.
String Literals: The text written in single, double, or triple quotes
represents the string literals in Python.
Some Interesting operations using operators that are often asked in Examinations:
Expression Output Explanation
2**3**2 512 Since ** is evaluated from
right to left, first 3**2 is
evaluated to 9 and 2**9
evaluated 512
10 or 20 10 If the first operand of an “or”
expression is true, return the
first operand. Otherwise,
evaluate and return the second
operand.
0 or 10 10 0 is False and hence second
operand is returned.
10 and 20 20 If the first operand of an
“and” expression is false,
return the first operand.
Otherwise, evaluate and return
the second operand.
Note: Any value is interpreted as “false” for the above purposes if it is 0, 0.0, None, False, or an
empty collection. Otherwise, it is interpreted as “true” for the above purposes. So, 10 and 20,
being nonzero numbers, are “true.”
25 % -4 -3 Python evaluates the
modulus with negative
numbers using the formula:
(a//b) * b + a%b == a
25//-4 gives -7 with floor
division.
-7 * -4 gives 28.
Hence a%b must be -3 to
make the expression
correctly equate to 25.
Note: The sign of the result
is always that of the divisor.
Questions:
Q.1 Which one of the following is not a valid identifier?
a) true
b) __init__
c) 20Decades
d) My_var
Q.2 Which of the following keywords is a python operator?
a) for
b) break
c) is
d) else
Q.3 What will be the output of the operation print("\\\\\\") ?
a) \\\\\\
b) \\\
c) \\
d) Error
Q.4 What will be the output of the expression print(10+20*10//2**3-5)
a) 30
b) 40
c) 1005
d) 130
Q.5 Evaluate the expression print(20%-3)?
a) -1
b) -2
c) 2
d) Error
Q.6 What will be the result of the expression True of False and not True or True
a) True
b) False
c) None
d) Error
Q.7 What will be the output of the following program?
a = {'A':10,'B':20}
b = {'B':20, 'A':10}
print(a==b and a is b)
a) True
b) False
c) None
d) Error
Q.8 Which of the following statements is false for python programming language?
a) Python is free and Open source.
b) Python is statically typed.
c) Python is portable.
d) Python is interpreted.
Flow of Control in Python
Python supports sequential flow of control.
Python supports branching flow of control using if, elif and else blocks.
Python supports iteration control using for loop and while loop.
Python if, elif and else blocks:
Python uses the relational and logical operators along with if and elif to create
conditional blocks that executes a set of python statements depending on the truth value
of the condition.
The beginning of a block starts from the next line just after the : symbol and the block is
indented.
if block
elif block
block
else block
Nested if block
block
With respect to the CBSE examination the students should thoroughly understand the construct
of if, elif, else and often a question comes where you need to identify the errors in each
program.
Q. Re-write the following program after removing errors, if any, and underline all the
corrections made.
a = input("Enter a number:")
b = int(input("Enter a number:"))
if a = b:
a+b=a
else
b=b+a
print(a,b)
Hint: There are four errors in the program
Python for loop:
Python for loop is used to iterate a set of python statements till a counter reaches its
limit.
Python for loop can also be used to iterate over a collection object (List, tuple)/ iterable
(string, dictionary) using membership operators.
Python while loop is used in situations where we have no idea as when the loop is going
to end since there are no counters.
else block in loop: The else block in a loop is executed when the break statement is not
encountered inside the loop.
Students are advised to go through the above content since various operations involving the
python data structures, user defined functions, data file handling and database interaction will
require a thorough understanding of iteration. In CBSE examination you may not get a direct
question from this topic except for a few MCQ or Assertion-Reasoning based question.
The following question is an ASSERTION AND REASONING based Questions. Mark
the correct choice as:
i) Both A and R are true, and R is the correct explanation for A
ii) Both A and R are true, and R is not the correct explanation for A
iii) A is True but R is False
iv) A is false but R is True
Q. ASSERTION: In python loop else block will be executed if the loop successfully
terminates after complete iteration.
REASON: A python loop else block will not execute if a break statement is encountered
in a loop.
Q. ASSERTION: A continue statement in a loop is mandatory.
REASON: A continue statement will skip the remaining statements in the loop after it is
encountered.
Python Strings
Python strings are a set of characters enclosed in single quotes, double quotes, or triple
quotes.
Python strings are immutable - Once a string is created, it cannot be changed. You can
create a new string with the desired modifications, but the original string remains
unchanged.
Python Strings are ordered: Strings maintain the order of characters in the sequence.
This means that the characters in a string have a definite order, and this order will not
change.
Python Strings are iterable: You can iterate over the characters in a string using loops
like for loops or comprehensions.
Characters in a String are indexable: Each character in a string can be accessed using an
index. Indexing starts from 0, so the first character of a string has an index of 0, the
second character has an index of 1, and so on.
String examples:
String operations:
Concatenation: More than one string can be joined using the (+) operator to create a
new string.
Slicing: A substring can be acquired from an existing string using the slicing
operation.
Str[start:stop:step]
Stop is not
reached.
Traversal: We can traverse a string using iteration and specifically using for loop.
o Iterate
using membership:
The start is 7
hence first two
M’s are not
included.
Python List
Ordered collection of objects - Lists maintain the order of elements as they are inserted.
Lists are mutable - Lists can be modified after creation. You can add, remove, or modify
elements freely.
Heterogenous - Lists can contain elements of different data types. For example, a list can
contain integers, strings, floats, and even other lists.
Dynamic - Lists in Python can grow or shrink in size dynamically. You can append new
elements, insert elements at specific positions, or remove elements as needed.
Indexed - Elements in a list are indexed with integers starting from 0. This allows for easy
access to individual elements using their index.
Nesting - Lists can contain other lists as elements, allowing for the creation of nested data
structures.
Built-in Methods - Python lists come with built-in methods for various operations like
sorting, reversing, searching, etc., making them versatile for a wide range of tasks.
Iterable - Lists can be used in iterations using loops (e.g., for loop)
Slicing - Lists support slicing operations, allowing you to extract sublists by specifying a
range of indices.
List Examples:
Accepting a list from User: eval() method can be used along with input() method to acquire a
list from the console.
List Operations: Like a String, python lists also support operations like Concatenation,
Replication, indexing, slicing and iteration. The only difference is that we can modify the
elements of a list using indexing, slicing and index-based iteration. In this study material we
shall see this component of python list that makes it unique mutable data structure.
Indexing of nested lists:
Changing list elements using indexing: We can change the elements of a list using indexing
and assignment operation.
Changing the list elements using slicing: We can change the replace the contents of a
list using slicing too. Given below are some interesting examples.
Changing list elements using index-based iteration: We can modify the elements of a
list using index-based iteration.
Deleting elements of a list using del command: del command may be used to delete
one or more than one element of a list either using indexing or using slicing.
methodName(list)
o List member methods: These methods have the format
listName.methodName()
clear() – Removes all the elements from a list and makes the list empty.
copy() – Creates a copy of the existing list and both list occupy different memory
locations.
pop(index) – Removes and returns the element from the given index.
remove(element): Removes the element from the given list without returning the
element. Return a ValueError is the element is not in the list.
Note: Unlike count() in String there is only one parameter to count() in list.
index(element, start) – Returns the index of the first occurrence of the given
element from the list.
If the start index is not given, the index() returns the index of first occurrence
only.
sort() – Sorts the list in ascending order. Unlike sorted() this method sorts the
same list and does not return a new list.
reverse() – Reverses the list based on value (ASCII value)
Questions:
Q.1 What will be the output of the following list operations?
data = [10,20,30,[40,50,60],[70,80]]
a) print(data[3]+data[-1])
print(data[-2][-2])
Q.2 What will be the output of the following python program:
data = [10,20,30, 60,70]
data[3:3]=[40,50]
print(data)
data.pop(3)
print(data)
data.extend([10,20])
print(len(data))
Q.3 Ganga is learning to use python Lists. Help her to get the answers of the following
operations based on the given list:
data = [10,20,30]
data[1:3]=[5,10]
print(data)
data.extend([3,4])
x =data.count(10)
print(data[x:])
data.sort()
print(data)
print(data.pop(2))
Q.4 Write a python program that accepts a list of integers from user and creates a new list
from the existing list containing all the numbers that have three or more digits.
Eg: for existing list [10,100, 99,200,1000] the new list should be [100,200,1000]
Q.5 Write a python program that accepts a list of countries from user and prints all the
countries whose number of alphabets is more than 5.
Q.6 Write a python program that accepts a list of integers from user and prints all the
integers that have 8 as the last digit.
Eg: for the list [10, 28, 8, 86, 98] the program should print 28 8 98
Q.7 For the given list
d=[10,30,20,15,45,50,80,90]
what will be the output of the following slicing operation:
d[2:7:2]
a) [20,15,45] b) [20, 45, 80] c) [30, 15, 50] d) [20, 45]
Python Dictionary
Python dictionaries are collection of key value pairs enclosed in {}
Python dictionaries are un-ordered.
Python dictionary keys are immutable (numbers, string, tuple)
Python dictionary values are mutable.
Dictionary Examples:
Dictionary Operations:
Displaying Values for a given Key: We can use dictName[key] to get the value.
sorted()
o Dictionary Member Methods: These methods are called using the syntax
dictName.methodName()
clear() – Removes all the elements from the dictionary and makes it empty.
copy() – Creates a copy of the existing dictionary.
get(key) – Returns the value for a given key.
keys() – Returns a view object containing the keys of the dictionary, that can be
converted to list using a list() method.
values() - Returns a view object containing the values of the dictionary, that can
be converted to list using a list() method.
items() - Returns a view object containing the key-value pairs as tuples of the
dictionary, that can be converted to list of tuples using a list() method.
update() – Used to add the contents of one dictionary as key-value pairs in
another dictionary.
pop(key) – Removes a key-value pair from a dictionary and returns only the
value.
popitem() – Reoves the last added key-value pair from the dictionary and returns
a tuple containing the removed key-value pair.
setdefault(key, value) – Returns the value for the key if the key is in the
dictionary, else adds the key-value pair to the dictionary.
Questions:
Q.1 Which of the following statements is False for a python dictionary?
a) Dictionary Keys can be created using another dictionary.
b) Dictionary values can be a dictionary.
c) Dictionary Values are mutable.
d) dict() function can be used to create a dictionary.
Q.2 What will be the output of the following program?
d={'A':10,'B':20,'C':30,'D':40}
del d['C']
print(d)
x = d.popitem()
print(x)
Questions 3 is an ASSERTION AND REASONING based Questions. Mark the correct
choice as:
i) Both A and R are true, and R is the correct explanation for A
ii) Both A and R are true, and R is not the correct explanation for A
iii) A is True but R is False
iv) A is false but R is True
Q.3 ASSERTION: A python dictionary remains the same even if we interchange the position
of key-value pairs.
REASONING: Dictionaries are un-ordered collection of key-value pairs.
Q.4 What will be the output of the following?
d = {"A":10, "B":20, "C":30, "A":40}
print(d)
a) {"A":10, "B":20, "C":30, "A":40}
b) {"A":40, "B":20, "C":30}
c) {"A":50, "B":20, "C":30}
d) KeyError
Q.5 Sapna wants to understand the concept of methods in a dictionary. Help her to find the
answers of the following operations on a python dictionary:
d = {'M':10, 'N':20, 'O':30, 'P':40}
r = d.popitem()
print(r)
x = d.pop('N')
print(x)
print(list(d.keys()))
d.setdefault('X',60)
print(d)
Q.6 Write a python program that increases the values by 10 for the dictionary alphabets as
keys and numbers as values where ever the key is a vowel.
Python Tuples
Python tuples are a collection of objects enclosed in ().
Python tuples are immutable.
Python tuples are ordered.
Python tuples are indexed like lists and strings.
Python tuples may contain heterogenous elements.
Python tuples can be nested.
Tuple examples:
Tuple operations: Like string and lists tuples too have concatenations, replication, indexing,
slicing and iteration operation. We are not going to discuss them here since you can follow the
list and strings to learn and practice them.
Tuple methods: Tuples have a few global methods and only two member methods.
o Global Methods – tuple(), min(), max(), len(), sum() and sorted(). We shall
discuss here only the sorted() method.
Python Functions
Python Function:- Functions is a block of code that is identified by its name. A function
can be executed by calling it. Writing the name of the function will call a function.
Functions are internally declared in a separate memory area. So a function can declare
variables with the same as declared in the outer part of the program.
Type of function :- Build in function ( all functions defined by python min() max() , lent()
etc, User-defined functions ( defined by the user )
Advantage of function :- (i) Reduces the size of the program (ii) improves reusability of
code
def keyword:- def keyword declares a user defined function followed by parameters
and terminated with a colon.
return keyword :- whenever the return keyword is executed inside a function it returns
the control back to its caller along with some value if passed explicitly. Writing return is
not compulsory and we can write as many return keywords as needed but only one return
keyword is executed.
Actual parameters :- When we call a function and pass some values to the function.
These passed values are called actual parameters.
Formal parameters :- The parameters declared in the header part of the function is
called formal parameters or the values received by the functions from its caller is called
formal parameters.
Default parameters:- It is formal parameters with the assignment of values. These
values are used if the caller does not provide value to that parameter. Remember default
parameters are written after not default parameters.
def << name of the >> (formal parameters ) : function body is always writer in
tab indentation
code hare
code here
out of scope of function. The function call can be placed after this part.
Example :-
def myfunction(a,b,c=10) : a,b and c is formal parameter and c is with default values
print(a,b,c)
return (a+b+c)
total = myfunction(10,20,30) # 10 12 and 30 are actual parameter.
Q. Write a function findbig that take 2 integers as parameters and returns the largest
value.
def findbig(a,b):
if a>b:
return a
else:
return b
x,y=5,10
bigvalue=findbig(x,y)
Practice questions:
Ans :- AlphabetDigit
Alphabet
(vi) def check(x,y):
if x != y:
return x+5
else:
return y+10
print(check(10,5)) Ans :- 15