PYTHON REVISION TOUR (12 Marks)
Python is a widely used high-level programming Arithmetic : +, -, *, /, %, **, //
language for general-purpose programming, Bitwise : &, ^, |
created by Guido Van Rossum and first released in Identity : is, is not
1991. My first program in Python is: Relational : >, >=, <, <=,!=, ==
print(“Hello World”) Logical : and, or
Python shell can be used in two ways, viz., Assignment : =
interactive mode and script mode. Membership : in, not in
TOKENS IN PYTHON (Lexical Unit) Arithmetic assignment: /=, +=, -=, *=, %=, **=, //=
Smallest individual unit in a program. PRECEDENCE OF ARITHMETIC OPERATORS
1. KEYWORDS PE(MD) (AS) = read PEMDAS
Predefined words with special meaning to the P=parenthesis () → E=exponential →M, D =
language processor; reserved for special multiplication and division → A, S=addition and
purpose and must not be used as normal subtraction
identifiers names. Example - True, for, if, else, elif, Ex: 12*(3%4)//2+6 = 24 (Try at your end)
from, is, and, or, break, continue, def, import etc. 5. PUNCTUATORS
2. IDENTIFIERS (1 mark) Punctuators are symbols that are used to organize
Names given to different parts of the program viz. sentence structure. Common punctuators used in
variable, objects, classes, functions, lists, Python are: ‘ “ # \ ( ) [ ] { } @ , : .
dictionaries and so forth. The naming rules: DATA TYPES
• Must only be a non-keyword word with no Means to identify type of data and set of valid
space in between. Example: salary, operations for it. These are
maxmarks 1. NUMBERS
• Must be made up of only letters, numbers To store and process different types of numeric
and underscore (_). Ex: _salary, _cs data: Integer, Boolean, Floating-point, Complex no.
• Can not start with a number. They can 2. STRING
contain numbers. Ex: exam21 Can hold any type of known characters i.e. letters,
Some valid identifiers are: numbers, and special characters, of any known
Myfile MYFILE Salary2021 _Chk scripted language. It is immutable datatype means
Invalid Identifies are: the value can’t be changed at place. Example:
My.file break 2021salary if “abcd”, “12345”,”This is India”, “SCHOOL”.
3. LITERALS -6 -5 -4 -3 -2 -1
Data items that have a fixed value. S C H O O L
1. String Literals: are sequence of characters 0 1 2 3 4 5
surrounded by quotes (single, double or triple)
S1=”Hello” S2=”Hello” S3=”””Hello””” 3. LISTS (2 marks)
2. Numerical Literals: are numeric values in Represents a group of comma-separated values of
decimal/octal/hexadecimal form. any datatype between square brackets. Examples:
D1=10 D2=0o56 (Octal) D3=0x12 (Hex) L1=list()
3. Floating point literals: real numbers and may L2=[1, 2, 3, 4, 5]
be written in fractional form (0.45) or exponent L3=[5, ‘Neha’, 25, 36, 45]
form (0.17E2). L4=[45, 67, [34, 78, 87], 98]
4. Complex number literal: are of the form a+bJ, In list, the indexes are numbered from 0 to n-1, (n=
where a, b are int/floats and J(or i) represents total number of elements). List also supports
− 1 i.e. imaginary number. Ex: C1=2+3j forward and backward traversal. List is mutable
5. Boolean Literals: It can have value True or datatype (its value can be changed at place).
False. Ex: b=False 4. TUPLE (1 mark)
6. Special Literal None: The None literal is used Group of comma-separated values of any data type
to indicate absence of value. Ex: c=None within parenthesis. Tuple are immutable i.e. non-
4. OPERATORS (3 marks) changeable; one cannot make change to a tuple.
Tokens that trigger some computation/action t1=tuple()
when applied to variables and other objects in an t2=(1, 2, 3, 4, 5)
expression. These are t3=(34, 56, (52, 87, 34), 67, ‘a’)
1|KVS – Regional Of fic e, JAI PUR | Sessi on 2020 -21
5. DICTIONARY (1 mark) S[2:6] NDRI From index number 2
The dictionary is an unordered set of comma to (6-1) i.e. 5.
separated key:value pairs, within { }, with the S[1:6:2] EDI From index 1 to 5
requirement that within a dictionary, no two keys every 2nd letter.
can be the same. Following are some examples of S[::2] KNRY From start to end …
dictionary: every 2nd letter.
d1=dict() S[::3] KDY From start to end …
d2={1:’one’, 2:’two’, 3:’three’} every 3rd letter.
d3={‘mon’:1, ‘tue’:2, ‘wed’:3} S[::-1] AYIRDNEK Will print reverse of
d4={‘rno’:1, ‘name’:’lakshay’, ‘class’:11} the string.
In dictionary, key is immutable whereas value is S[ : -1] KENDRIY Will print entire string
mutable. except last letter
STRING PROCESSING AND OTHER FUNCTIONS S[ -1] A Will print only last
STRING REPLICATION letter
When a string is multiplied by a number, string is S[-5::] DRIYA From index no -5 to
replicated that number of times. end of the string.
Note: Other datatype – list and tuple also show S[-7:-4:] END From index no -7 to -5.
the same behavior when multiplied by an
integer number.
OTHER FUNCTIONS
length() istitle()
>>> STR=’Hi’
>>> print(STR*5) startswith() endswith()
>>>HiHiHiHiHi count(word) isspace()
>>> L=[1, 2] swapcase() find()
>>> print(L*5) lstrip() rstrip()
>>> [1,2,1,2,1,2,1,2,1,2] strip()
>>> t=(1, 2)
>>> print(t*5) LIST PROCESSING AND OTHER OPERATIONS
>>> (1,2,1,2,1,2,1,2,1,2) CREATING LIST
1) Empty List
STRING SLICE (2 marks) >>>L=[] OR >>> L=list()
String Slice refers to part of a string containing 2) From existing sequence
some contiguous characters from the string. The >>>st=’HELLO’
syntax is str_variable[start:end:step]. >>> L1=list(st) # from a string
start: from which index number to start >>> t=(1, 2, 3)
end: upto (end-1) index number characters will >>> L2=list(t) # from a tuple
be extracted 3) from Keyboard entering element one by one
step: is step value. (optional) By default it is 1 >>> L=[]
Example : Suppose S='KENDRIYA' >>> for i in range(5):
Backward - - - - - - - - n=int(input(‘Enter a number :’))
Index no 8 7 6 5 4 3 2 1 L.append(n)
Character K E N D R I Y A
TRAVERSING A LIST
Forward
>>> L=[1, 2, 3, 4, 5]
Index no 0 1 2 3 4 5 6 7
>>> for n in L:
print(n)
Command Output Explanation
JOINING LISTS
S KENDRIYA Will print entire string. >>> L1=[1, 2, 3]
S[:] KENDRIYA Will print entire string. >>> L2=[33, 44, 55]
S[::] KENDRIYA Will print entire string. >>> L1 + L2 # output: [1, 2, 3, 33, 44, 55]
SLICING THE LIST (1 mark)
S[2] N Will print element at
>>> L=[10, 11, 12, 13, 14, 15, 16, 18]
index no 2.
>>> seq=L[2:6]
2|KVS – Regional Of fic e, JAI PUR | Sessi on 2020 -21
# it will take from index no 2 to (6-1) i.e. 5 DELETING ELEMENTS FROM DICTIONARY
>>> seq # output: [12, 13, 14, 15] >>> del d[3]
General syntax for slicing is L[start : end : step] # will delete entire key:value whose key is 3
APPENDING ELEMENT >>> print(d) # op: {1: 'one', 2: 'two', 4: 'four'}
>>> L=[10, 11, 12] OTHER FUNCTIONS
>>>L.append(20) # Will append 20 at last Here is a list of functions to recall them which work
>>> L # output : [10, 11, 12, 20] on dictionaries.
>>>L.append([4,5]) pop(key) len() values()
# Appended data will be treated as a single element items() keys() update()
>>> L # output: [10, 11, 12, 20, [4, 5]]
EXPANDING LIST WORKING WITH FUNCTIONS
>>> L=[10, 11, 12] Block of statement(s) for doing a specific task.
>>>L.extend([44,55]) Advantages of function:
# Will extend given item as separate elements ➢ Cope-up with complexity
>>> L # output: [10, 11, 12, 44, 55]➢ Hiding details – Abstraction
UPDATING LIST ➢ Fewer lines of code - lessor scope for bugs
>>> L=[10, 11, 12] ➢ Increase program readability
# Suppose we want to change 11 to 50 ➢ Re-usability of the code
>>> L[1]=50 DEFINING AND CALLING FUNCTION
>>> L # output: [10, 50, 12] In python, a function may be declared as:
DELETING ELEMENTS def function_name([Parameter list]) :
del List[index]# Will delete the item at given index “””Doc-string i.e. documentation of fn”””
del List[start : end]# Will delete from index no start Body of the function
to (end-1) return value
>>> L=[x for x in range(1,11)] Remember: Implicitly, Python returns None,
>>> L # list is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
which is also a built-in, immutable data type. Ex:
>>> del L[2:5] >>> def f(a,b):
>>> L # now list is [1, 2, 6, 7, 8, 9, 10] “””demo of a function””” #doc-string
OTHER FUNCTIONS (1 mark) c=a+b
len() clear() sum(List) return c
pop(index) remove() min(List) >>>f(10, 20) # calling of function
insert(pos, value) sort() max(List)
def is a keyword to declare a function
index(value) pop() count()
f is the name of the function
a, b – parameter/argument of the function
TUPLE Vs LISTS return is a keyword
Tuples (is immutable) List (Mutable) Functions can be categorized in three types:
We can not change we can change the 1. Built-in function 2. Modules 3. User-defined
value in place. value in place BUILT-IN FUNCTION
➢ Pre-defined functions available in Python.
DICTIONARY ➢ Need not import any module (file).
Dictionaries are a collection of some unordered ➢ Example of some built-in functions are:
key:value pairs; are indexed by keys (keys must be str(), eval(), input(), min(), max(), abs(),
of any non-mutable type). type(), len(), round(), range(), dir(), help()
TRAVERSING A DICTIONARY MODULES
>>> d={1:’one’, 2:’two’, 3:’three’} ➢ Module in Python is a file (name.py) which
>>> for key in d: contains the definition of variables and
print(key, “:”, d[key], sep=’\t’) functions. A module may be used in other
1 : one 2 : two 3 : three programs. We can use any module in two ways
ADDING ELEMENT TO DICTIONARY 1. import <module-name>
>>>d[4]=’four’ # will add a new element 2. from <module-name> import <func-name>
>>> print(d) Some well-known modules are: math, random,
{1: 'one', 2: 'two', 3: 'three', 4: 'four'} matplotlib, numpy, pandas, datetime
3|KVS – Regional Of fic e, JAI PUR | Sessi on 2020 -21
USER-DEFINED FUNCTIONS findSum(p,q,r) #output - Sum is 600
➢ UDFs are the functions which are created by findSum(p,q) #output - Sum is 310
the user as per requirement. findSum(r) #output - Sum is 330
➢ After creating them, we can call them in any findSum(q,r) #output - Sum is 510
part of the program. findSum() #output - Sum is 60
➢ Use ‘def’ keyword for UDF. 3. KEYWORD ARGUMENTS
ACTUAL AND FORMAL PARAMETER/ ARGUMENT we can pass arguments value by keyword, i.e. by
Formal Parameter appear in function definition passing parameter name to change the sequence of
Actual Parameter appear in function call arguments, instead of their position. Example:
statement. def print_kv(kvnm, ronm):
Example: print(kvname,'comes under',roname,'region')
def findSum(a, b): # a, b formal parameter
print(‘The sum is ‘,(a+b)) #main-program
#main-program print_kv(kvnm='Rly Gandhidham', ronm='Ahmd')
X, Y=10,30 print_kv(ronm='Jaipur', kvnm='Bharatpur')
findSum(X, Y) # X, Y are actual parameter
4. VARIABLE LENGTH ARGUMENTS
VARIABLE SCOPE In certain situations, we can pass variable number
➢ Arguments are local of arguments to a function. Such types of
➢ Variable inside functions are local arguments are called variable length argument.
➢ If variable is not defined , look in parentThey are declared with * (asterisk) symbol.
scope def findSum(*n):
➢ Use the global statement to assign to global sm=0
variables for i in n:
TYPES OF ARGUMENTS sm=sm+i
Python supports four types of arguments: print('Sum is ',sm)
1. Positional 2 Default #main-program
3. Keyword 4. Variable Length
findSum() #output – Sum is 0
1. POSITIONAL ARGUMENTS findSum(10) #output – Sum is 10
Arguments passed to function in correct positional
findSum(10,20,30) #output – Sum is 60
order. If we change the position of their order, then
PASSING STRINGS TO FUNCTION
the result will change. def countVowel(s):
>>> def subtract(a, b): vow='AEIOUaeiou'
print(a - b) ctr=0
>>> subtract(25, 10) # output: 15 for ch in s:
>>> subtract(10, 25) # output: - 15 if ch in vow:
2. DEFAULT ARGUMENTS ctr=ctr+1
To provide default values to positional print('Number of vowels in', s ,'are', ctr)
arguments; If value is not passed, then default #main-program
values used. data=input('Enter a word to count vowels :')
Remember - If we are passing default arguments, countVowel(data)
then do not take non-default arguments, otherwisePASSING LIST TO FUNCTION
it will result in an error. def calAverage(L):
sm=0
def findSum(a=30, b=20, c=10): for i in range(len(L)):
print('Sum is ',(a+b+c)) sm=sm+L[i]
''' av=sm/len(L)
def mySum(a=30, b=20, c): return av
print('Sum is ',(a+b+c)) #main-program
#Error that non-default argument follows default marks=[25, 35, 32, 36, 28]
arguments print('Marks are :',marks)
''' avg=calAverage(marks)
#main-program print('The average is', avg)
p, q, r =100, 200, 300
4|KVS – Regional Of fic e, JAI PUR | Sessi on 2020 -21