Python
Python
Tokens in Python
In a passage of text, individual words and punctuation marks are called tokens
or lexical units or lexical elements. The smallest individual unit in a program is
known as Tokens. Python has following tokens
Keywords
Identifiers(Name)
Literals
Operators
Punctuators
Keywords in Python
There are 33 keywords in Python 3.7. This number can vary slightly in the course
of time. All the keywords except True, False andNone are in lowercase and they
must be written as it is. The list of all the keywords is given below.
Operators in Python
Python language supports the following types of operators-
• Arithmetic Operators
• Relational Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Operators in Python: Arithmetic
Assume a=10 and
b=20
Bitwise operator works on bit and performs bit by bit operation. Assume if A=60
and B=13; now in binary they will be as follows A(60)=00111100
B(13)=00001101
a&b = 0000 1100 (Use of bitwise Binary AND) a|b = 0011 1101 (Use of bitwise
Binary OR) a^b = 0011 0001 (Use of bitwise XOR)
~a = 1100 0011 (Use of ones complement)
Operators in Python: Membership
list=[1, 2, 3, 4, 5] Output
Control statements are used to control the flow of execution depending upon
the specified condition/logic. There are three types of control statements-
1. Decision Making Statements (if, elif, else)
2. Iteration Statements (while and for Loops)
3. Jump Statements (break, continue, pass)
Decision Making Program Output
Statements(if, elif, a=int(input("Enter any Enter any integer
else) Syntax: integer number :")) number :5
if(logic): if(a==0): Number is
Statement/s elif(logic): print("Number is Zero") Positive
Statemet/s else: elif(a>0):
Statement/s print("Number is
Positive") else:
print("Number is
negative")
Iteration Statements Program: Output
(while loop) n=1 while(n<4): Govind Govind
Syntax: print("Govind ", end=“ “) Govind
while(condition): n=n+1
Statement/s
Iteration Statements Program Output
(for loop) for i in range(1,6): print(i, 1 2 3 4 5
Syntax: end=' ')
for value in sequence:
Statements
Jump Statements Program Output
(break, continue, for i in range(1,11): 1 2 hello 4 6 7
pass) if(i==3):
Syntax: print("hello", end=' ')
for val in sequence: if continue
(val== i): if(i==8): break if(i==5):
break pass
if (val== j): continue else:
if (val== k): print(i, end=' ');
pass
List in Python
Creating a list and accessing its Output
elements
a=[10,20,'abc',30,3.14,40,50] [10, 20, 'abc', 30, 3.14, 40, 50]
print(a) 10 20 abc 30 3.14 40 50
for i in range(0,len(a)): 50 40 3.14 30 abc 20 10
print(a[i], end=' ') 50 40 3.14 30 abc 20 10
print('\n') 50 40 3.14 30 abc 20 10
for i in range(len(a)-1,-1,-1):
print(a[i], end=' ')
print('\n')
for i in a[::-1]:
print(i, end=' ')
print('\n')
for i in reversed(a):
print(i, end=' ')
Tuple in Python
It is a sequence of immutable objects. It is just like a list. Difference between a
tuple and a list is that the tuple cannot bechanged like a list. List uses square
bracket whereas tuple use parentheses.
L=[1,2,3,4,5] Mutable Elements of list can be changed T=(1,2,3,4,5)
Immutable Elements of tuple can not be changed
Creating a tuple and accessing its Output
elements
a=(10,20,'abc',30,3.14,40,50) (10, 20, 'abc', 30, 3.14, 40, 50)
print(a) 10 20 abc 30 3.14 40 50
for i in range(0,len(a)): 50 40 3.14 30 abc 20 10
print(a[i], end=' ') 50 40 3.14 30 abc 20 10
print('\n') 50 40 3.14 30 abc 20 10
for i in range(len(a)-1,-1,-1):
print(a[i], end=' ')
print('\n')
for i in a[::-1]:
print(i, end=' ')
print('\n')
for i in reversed(a):
print(i, end=' ')
Function Description
tuple(seq) Converts a list into a tuple.
min(tuple) Returns item from the tuple
with min value.
max(tuple) Returns item from the tuple
with max value.
len(tuple) Gives the total length of the
tuple.
cmp(tuple1,tuple2) Compares elements of both
the tuples.
Dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store
data values along with the keys Dictionary holds key:value pair. Key value is
provided in the dictionary to make it more optimized. Each key-value pair in a
Dictionary is separated by a colon:, whereas each key is separated by a ‘comma’.
dict={ “a": “alpha", “o": “omega", “g": ”gamma” }
print("\n all values in the dictionary all keys and values in the
using values() method:") dictionary using
items()method:
for i in D.values(): print(i, end=' ')
1 AAA 2 BBB 3 CCC
print("\n all keys and values in the
dictionary using items() method:")
for k, v in D.items():
print(k, v, end=' ')
Very Short Answer Type Questions (1-Mark)
1. Find the valid identifiers from the following : a. Myname b. My name c.
True d. Myname_2 Ans: Myname and Myname_2 are valid identifiers
2. What is None literal in Python?
Ans: Python has one special literal called “None”. It is used to indicate
something that has not yet been created. It is a legalempty value in Python.
3. Can List be used as keys of a dictionary?
Ans: No, List can’t be used as keys of dictionary because they are mutable. And
a python dictionary can have keys of only immutable types.
4. Find the invalid identifiers from the following
a) def b) For c) _bonusd) 2_Name
Ans: def and 2_Name are invalid identifiers
5. Find the output -
>>>A = [17, 24, 15, 30]
>>>A.insert( 2, 33)
>>>print ( A [-4])
Ans: 24
6. Name the Python Library modules which need to be imported to invoke
the following functions:
(i) ceil() (ii) randrange()
Ans: (i) math (ii) random
7. Which of the following are valid operator in Python:
(i) */(ii) is(iii) ^ (iv) like
Ans: is and ^ are valid operators in python
8. What will be the result of the following code?
>>>d1 = {“abc” : 5, “def” : 6, “ghi” : 7}
>>>print (d1[0])
(a) abc (b) 5 (c) {“abc”:5} (d) KeyError
Ans: KeyError
9. Given the lists Lst=[‟C‟,‟O‟,‟M‟,‟P‟,‟U‟,‟T‟,‟E‟,‟R‟] , write the output
of:
print(Lst[3:6])
Ans: [‟P‟,‟U‟,‟T‟]
10. Which of the following is valid arithmetic operator in Python:
(i) // (ii)? (iii) < (iv) and
Ans: //
Short Answer Type Questions (2-Marks)
1. What are tokens in Python ? How many types of tokens are allowed in
Python ? Examplify your answer.
Ans: The smallest individual unit in a program is known as a Token. Python has
following tokens:
1. Keywords — Examples are import, for, in, while, etc.
2. Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
3. Literals — Examples are "abc", 5, 28.5, etc.
4. Operators — Examples are +, -, >, or, etc.
5. Punctuators — ' " # () etc.
2. Can nongraphic characters be used in Python ? How ? Give examples to
support your answer.
Ans: Yes, nongraphic characters can be used in Python with the help of escape
sequences. For example, backspace is represented as \b, tab is represented as \
t, carriage return is represented as \r.
3. Predict the output:
for i in range( 1, 10, 3): print(i)
Ans: 1
4
7