0% found this document useful (0 votes)
9 views26 pages

Python

Computer science

Uploaded by

avneetkulwinder
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
9 views26 pages

Python

Computer science

Uploaded by

avneetkulwinder
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 26

CHAPTER 1: REVISION OF THE BASICS OF PYTHON

 Python (a computer language) :


 Python is a powerful and high level language and it is an interpreted
language.
 It is widely used general purpose, high level programming language
developed by Guido van Rossum in 1991.
 Python has two basic modes: interactive and script.
 In interactive mode (python.exe/py.exe), the result is returned
immediately after pressing the enter key.
 In script mode (IDLE), a file must be created and saved before
executing the code to get results.
 Python’s Features:
 Easy to use Object oriented language
 Expressive language
 Interpreted Language
 Its completeness
 Cross-platform Language
 Fee and Open source
 Variety of Usage / Applications
Basics of Python: Output
Simple Hello world Program Output
print('hello world') print("HELLO hello world HELLO WORLD
WORLD")
Declaring/Defining variable Output
x=30 y=20 50
z=x+y print(z) a,b=4,5 45
print(a,b)
Output Formatting Output
x,y=20,30 The addition of x and y is
z=x+y 50 The addition of 20 and
30 is 50
print("The addition of x and y is ", z)
print("The addition of ",x,"and ", y, "is The addition of 20 and 30
",z) is 50

print("The addition of %d and %d is %d"


%(x,y,z))
name="XYZ" age=26 salary=65748.9312 Output
print("The age of %s is %d and salary is The age of XYZ is 26 and
%.2f" salary is 65748.93
%(name,age,salary))
Basics of Python: Input

Accepting input without prompt Output


X=10 10
print(X)
Accepting input with prompt Output
X=input(“Enter your name : ") print("My Enter your name : Yogesh
name is ",X) My name is Yogesh
Accepting formatted input (Integer, Output
float, etc.) age=int(input("Enter your age Enter your age :16 Enter
: ")) height=float(input("Enter your your height : 5.5 Your age
height : ")) print("Your age is : ",age) is : 16
print("Your height is : ",height) Your height is : 5.5

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

Operators in Python: Relational


Relational Operators are used to show relationship between two values or
variables. Following are the relational operators:
< (less than), >(greater than) , <= (less than equal to), >= (greater than equal
too) ,!= (Not equal to) and = = (equality checkoperator)

Operators in Python: Logical


Operators in Python: Assignment
Operators in Python: Bitwise

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

print("Elements in the list: ",list) Elements in the list: [1, 2, 3, 4, 5]


if(3 in list): 3 available in the list

print(3, "available in the list")


else:

Operators in Python: Identity


a,b = 20,20 Output
print("ID of a :",id(a)," ID of ID of a : 1442604432 ID of
b :",id(b)) b : 1442604432
if(a is b): a and b have same
identity
print("a and b have same
identity")else:
Control Statements in Python

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” }

# Creating an empty Dictionary Output


Dict = {} Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict) Dictionary with the use of
# Creating a Dictionary with Integer Integer Keys:
Keys {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'}
Dict = {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'} Dictionary with the use of
print("\nDictionary with the use of Mixed Keys:
Integer Keys: ") print(Dict) {'Name': 'Govind', 1: [10, 11,
# Creating a Dictionary with Mixed 12, 13]}
keys Dictionary with the use of
Dict = {'Name': ‘Govind', 1: [10, 11, dict():
12, 13]} {1: 'AAA', 2: 'BBB', 3: 'CCC'}
print("\nDictionary with the use of Dictionary with each item as a
Mixed Keys: ") print(Dict) pair:
# Creating a Dictionary with dict() {1: 'AAA', 2: 'BBB'}
method
D=dict({1: 'AAA', 2: 'BBB', 3:'CCC'})
print("\nDictionary with the use of
dict(): ") print(D)
# Creating a Dictionary with each
item as a Pair
D=dict([(1, 'AAA'), (2, 'BBB')])
print("\nDictionary with each item as
a pair: ")
print(D)
# Creating an empty DictionaryDict = Empty Dictionary:
{} {}
print("Empty Dictionary: ")print(Dict) Dictionary after adding 3
# Adding elements one at a time elements:
Dict[0] = ‘Govind' {0: 'Govind', 2: ‘Prasad', 3:
Dict[2] = ‘Prasad' Dict[3] = ‘Arya’ ‘Arya’} Dictionary after adding
print("\nDictionary after adding 3 3 elements:
elements: ") print(Dict) {{0: 'Govind', 2: ‘Prasad', 3:
# Adding set of values# to a single ‘Arya’} , 'V':
Key Dict['V'] = 1, 2 (1, 2,)}
print("\nDictionary after adding 3 Updated dictionary:
elements: ") print(Dict) {{0: 'Govind', 2: ‘Prasad', 3:
# Updating existing Key's Value ‘Arya’} , 'V':
Dict[‘V’] = 3,4 (3, 4,)}
print("\nUpdated dictionary: ")
print(Dict)
# Creating a Dictionary Output
D = {1: ‘Prasad', 'name': ‘Govind', 3: Accessing a element using
‘Arya'} key:Govind Accessing a
element using key:Prasad
Accessing a element using
# accessing a element using key get:Arya
print("Accessing a element using
key:") print(D['name'])

# accessing a element using key


print("Accessing a element using
key:") print(D[1])

# accessing a element using get()


method print("Accessing a element
using get:") print(D.get(3))
D={1:'AAA', 2:'BBB', 3:'CCC'} Output
print("\n all key names in the all key names in the
dictionary, one by one:") for i in D: dictionary, one by one: 1 2 3
print(i, end=' ') all values in the dictionary,
print("\n all values in the dictionary, one by one: AAA BBB CCC
one by one:") for i in D: all keys in the dictionary using
print(D[i], end=' ') keys() method:

print("\n all keys in the dictionary 123


using keys() method:") all values in the dictionary
for i in D.keys(): print(i, end=' ') using values() method:
AAA BBB CCC

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

4. What will be the output of the following snippet?


values =[ ]
for i in range (1,4):
values.append(i) print(values)
Ans: [1,2,3]
5. Convert the following for loop in while loop
for i in range(1,10,2): print(i)
Ans:
i=1 while(1<10):
print(i) i+=2
6. Predict the output of the following code snippet:
a=10,20,30
b=list(a) b[2]=[40,50]
print(a) print(b)
Ans: (10,20,30)
[10,20,[40,50]]
7. If given A=2,B=1,C=3, What will be the output of following expressions:
(i) print((A>B) and (B>C) or(C>A))
(ii) print(A**B**C) Ans: (i) True (ii) 2
8. What possible outputs(s) are expected to be displayed on screen at the
time of execution of the program from the following code? Also specify
the maximum values that can be assigned to each of the variables FROM
and TO.
import random AR=[20,30,40,50,60,70]
FROM=random.randint(1,3) TO=random.randint(2,4)
for K in range(FROM,TO): print (AR[K],end=”#“)
(i)10#40#70#(ii)30#40#50# (iii)50#60#70#(iv)40#50#70#
Ans: Maximum value of FROM = 3 Maximum value of TO = 4
(ii) 30#40#50#
9. Rewrite the following Python program after removing all the syntactical
errors (if any), underlining each correction:
x = input("Enter a number") if x % 2 =0:
print (x, "is even") elseif x<0:
print (x, should be positive) else;
print (x, "is odd")
Ans:
x = input("Enter a number") # int(input(“Enter a number”)) if x % 2 =0:
print (x, "is even")
elseif x<0: # elif
print (x, should be positive) # print (x, "should be positive")
else; # else:
print (x, "is odd")

Application Based Questions ( 3 Marks)

1. Predict the output of the following Code:


for i in range(3): if i==2:
continue print(i**2)
else:
print("Bye")
Ans:
0
1
Bye
2. Predict the output of the following Code:
for i in range(1,11,3): if i==10:
break print(i**2)
else:
print("Bye")
Ans:
1
16
49
3. Predict the output of the following Code:
for i in range(-10,0): if i%3==0:
print(i,end=' ') print(i**2)
Ans:
-9 81
-6 36
-3 9

You might also like