Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

SOLUTIONS TO PYTHON QUESTION BANK:

PART-(A)
(1) List the features of Python Programming language?

(a)Easy to code programming language.

(b)Free and Open Source

(c)Object-Oriented Language

(d)high level language

(e)dynamically types

(f)platform independent

(g)portable

-------------------------------------------------------------------------------------------------------------------------------------

(2) State the reasons for Python‟s popularity?

First and foremost reason why Python is much popular because it is highly productive as compared
to other programming languages like C++ and Java. ... Python is also very famous for its simple
programming syntax, code readability and English-like commands that make coding in Python lot
easier and efficient.

Python is a general purpose programming language. Hence, you can use the programming language
for developing both desktop and web applications. Also, you can use Python for developing complex
scientific and numeric applications. Python is designed with features to facilitate data analysis and
visualization.

The python language is one of the most accessible programming languages available because it has
simplified syntax and not complicated, which gives more emphasis on natural language. Due to its
ease of learning and usage, python codes can be easily written and executed much faster than other
programming languages.

------------------------------------------------------------------------------------------------------------------------------------ --

(3) Write any five applications in which Python is popularly used?

Web Development. Python can be used to make web-applications at a rapid rate. ...

Game Development. Python is also used in the development of interactive games. ...

Machine Learning and Artificial Intelligence. ..Data Science and Data Visualization. ..

Desktop GUI. ..
#OR

Web DevelopmentGame, DevelopmentMachine ,Learning and Artificial IntelligenceData Science and


Data VisualizationDesktop GUIWeb Scraping ApplicationsBusiness ApplicationsAudio and Video
ApplicationsCAD ApplicationsEmbedded Applications

#OR

Real-world Applications of Python

Web Development. ...

Game Development. ...

Scientific and Numeric Applications. ...

Artificial Intelligence and Machine Learning. ...

Software Development. ...

Enterprise-level/Business Applications. ...

Education programs and training courses. ...

Language Development.

----------------------------------------------------------------------------------------------------------------------------------- ---

(4) Write any three unique features of Python?

No compiler is required

Python is Dynamically Typed.

Python supports both procedure oriented and object oriented programming which is one of the key
python features.

It has slicing operations.

It is an abstract data type and holds no values.

-------------------------------------------------------------------------------------------------------------------------------------

(5) Evaluate the following expressions? i. 2 ** 6 // 8 % 2

ii. 7 % 7 + 7 // 7 -7 * 7

(A)

(i) 64//8%2

=8%2=0

(ii) 7%7+7//7-7*7 = 7%7+1-7*7= 7%7+1-49= 0+1-49= -48

--------------------------------------------------------------------------------------------------------------------------------------

(6) Identify which of the following is an invalid variable name?

i. hELLO
ii. 2020_Dec

iii. _basic

iv. basic-hra

v. #xyz

(A)

ii.2020_dec not valid because we cant start with number

iv. basic-hra is wrong because we cant use –

v. #xyz is wrong because we cant use #

----------------------------------------------------------------------------------------------------------------------------- ---------

(7) Evaluate the following expressions? i. min(6,8,5,10)

ii. round(20.644336,2)

iii. pow(2,5)

iv. bin(15)

v. int(-3.33)

(A)

(i). 5

(ii). 20.64

(iii)32

(iv) binary equivalent of 15= 1111=’0b1111’

(v). -3

(8) Identify the correct arithmetic expression in Python?

i .11(12+13)

ii. (5*6)(7+8)

iii. 4*(3-2)

iv. 5***3

(A)

(i) wrong because there is no * and the system wont understand that we should multiply it.

(ii)(5*6)(7+8)= (30)(15)→ wrong because the system dosent know what to do after this as * is not
mentioned.

(iii)4*(3-2)= 4*1=4

(iv) 5***3= 125


----------------------------------------------------------------------------------------------------------------------------- ---------
(9) State the keyword which is used to remove a variable?

The keyword which is used to remove a variable is ‘del’.

----------------------------------------------------------------------------------------------------------------------------- ---------
(10)

To be discussed later.

(11) Find the output of the following?

i. trunc(-2.8)

ii. floor(-0.5)

iii. ceil(0.2)

(A)

(i). trunc(x) - removes all the trailing decimal places in x. It just removes all the decimals.

Import math

trunc(-2.8)= -2

(ii) floor(x) - rounds number to the next lowest integer import math

Import math

math.floor(-0.5)=-1

(iii) ceil(x) - rounds number to the next highest integer

Import math

math.ceil(0.2)=1

(12) s='Python@123'

i. print(s.isalpha()-False

ii. print(s.islower())-False

iii. print(s.isupper())-False

iv. print(s.isdigit())-False

--------------------------------------------------------------------------------------------------------------------------------------

#13-

'''str ='Hello'

print(str[0])#H

print(str[4])#o

print(str[-0])#H
print(str[-5])#o

print(str[-1])#o'''

----------------------------------------------------------------------------------------------------------------------------- ---------

#14-

'''Str='Welcome to IARE'

print(Str[3:100])#come to IARE

print(Str[4:])#ome to IARE

print(Str[100])#IndexError: string index out of range'''

----------------------------------------------------------------------------------------------------------------------------- ---------

#15-

'''print('e' in 'Hello')#True

print('z' in 'Hello')#False

print('lo' in 'Hello')#True'''

-------------------------------------------------------------------------------------------------------------------------------- ------

#16-

'''a=10

b=12

c=0

print(a != 6 and b > 5)#True

print(a == 9 or b < 3)#False

print(not ( a < 10 ))#True

print(not (a > 5 and c)#True'''

----------------------------------------------------------------------------------------------------------------------------- --------

#17-

'''ch=set('Hello')#{'l', 'e', 'H', 'o'}

print(ch)

print(ch.add('hai'))#none

print(ch.remove('H'))#none

print(ch.clear())#none'''

----------------------------------------------------------------------------------------------------------------------------- ---------

#18-
'''lst1=[10,20,30,40,50]

print(lst1.append(60))#none

print(lst1.pop())#60

print(lst1.pop(3))#40

print(lst1.insert(3,45))#none'''

----------------------------------------------------------------------------------------------------------------------------- ---------

#19-

'''d1={'Mango' : 30,'Guava': 20}

print(d1)#{'Mango': 30, 'Guava': 20}

print(d1.keys())#dict_keys(['Mango', 'Guava'])

print(d1.values())#dict_values([30, 20])

print(d1.clear())#none'''

----------------------------------------------------------------------------------------------------------------------------- ---------

#20-

'''t1=tuple('HYD')

print(t1)#('H', 'Y', 'D')

print(t1*2)#('H', 'Y', 'D', 'H', 'Y', 'D')

print(t1[-1])#D

print(t1[::-1])#('D', 'Y', 'H')'''

---------------------------------------------------------------END OF part(A)--------------------------------------------

PART(B)
1. Write the features and applications of Python programming language
Features in Python:-
a. Easy to code: Python is a high-level programming language
b. Free and Open Source
c. Object-Oriented Language
d. GUI Programming Support
e. High-Level Language
f. Extensible feature
g. Python is Portable language
h. Python is Integrated language
------------------------------------------------------------------------------------------------------------
2. List the various operators supported in Python?
Python language supports the following types of operators.
a. Arithmetic Operators.
b. Comparison (Relational) Operators.
c. Assignment Operators.
d. Logical Operators.
e. Bitwise Operators.
f. Membership Operators.
g. Identity Operators
----------------------------------------------------------------------------------------------------------------------------- ---------

3. #program to display x^y


Eg:-2^5=32
x=int(input('enter x value'))
y=int(input('enter y value'))
print(pow(x,y))
----------------------------------------------------------------------------------------------------------------
4. #program to greet the user
first_name=input('enter your first name:')
last_name=input('enter your last name:')
print("Greetings!!!",first_name,last_name)
----------------------------------------------------------------------------------------------------------------

5. #amount of grosssalary
basic_salary=int(input("enter basic salary:"))
DA=40/100*basic_salary
print('DA',DA)
HRA=20/100*basic_salary#HRA=house rent allowance
print('HRA',HRA)
gross_salary=basic_salary+DA+HRA
print('GROSS_SALARY',gross_salary)
----------------------------------------------------------------------------------------------------------------

6. #program for conversion of given distance into various units


#CM=centimeters
#M=meters
#KM=kilometers
#Ft=feet
#Inc=inches
KM=float(input('enter the distance between cities in kilometers:'))
M=KM*1000
Ft=KM*3280
Inc=KM*10.079
CM=KM*100000
print('distance in meters',M)
print('distance in feets',Ft)
print('distance in inches',Inc)
print('distance in centimeters',CM)
----------------------------------------------------------------------------------------------------------------

7. # PROGRAM TO CONVERT TEMPERATURE FROM FAHRENHEIT TO


CELSIUS
#F=temperature in fahrenheit
#C=temperature in celsius
F=int(input('enter the temperature of city:'))
C=(F-32)*5/9
print('temperature in fahrenheit:',F)
print('temperature in celsius:',C)
----------------------------------------------------------------------------------------------------------------

8. Explain with example membership and identity operators in Python?


(a)Membership operators are operators used to validate the
membership of a value. It tests for membership in a sequence, such
as strings, lists, or tuples.
1. In Operator : The ‘in’ operator is used to check if a value exists
in a sequence or not. Evaluates to true if it finds a variable in the
specified sequence and false otherwise.

# Python program to illustrate

# Finding common member in list

# using 'in' operator

list1=[1,2,3,4,5]

list2=[6,7,8,9]

for item in list1:

if item in list2:
print("overlapping")

else:

print("not overlapping")

Output:
not overlapping
Same example without using in operator:

# Python program to illustrate

# Finding common member in list

# without using 'in' operator

# Define a function() that takes two lists

def overlapping(list1,list2):

c=0

d=0

for i in list1:

c+=1

for i in list2:

d+=1

for i in range(0,c):

for j in range(0,d):

if(list1[i]==list2[j]):

return 1

return 0
list1=[1,2,3,4,5]

list2=[6,7,8,9]

if(overlapping(list1,list2)):

print("overlapping")

else:

print("not overlapping")

Output:
not overlapping
1. ‘not in’ operator- Evaluates to true if it does not find a variable in the
specified sequence and false otherwise

# Python program to illustrate

# not 'in' operator

x = 24

y = 20

list = [10, 20, 30, 40, 50 ];

if ( x not in list ):

print("x is NOT present in given list")

else:

print("x is present in given list")

if ( y in list ):

print("y is present in given list")

else:
print("y is NOT present in given list")

(b) Identity operators


In Python are used to determine whether a value is of a certain class or
type. They are usually used to determine the type of data a certain
variable contains.
There are different identity operators such as
1. ‘is’ operator – Evaluates to true if the variables on either side of the
operator point to the same object and false otherwise.

# Python program to illustrate the use

# of 'is' identity operator

x =5

if (type(x) is int):

print("true")

else:

print("false")

Output:
True

2. ‘is not’ operator – Evaluates to false if the variables on either side of


the operator point to the same object and true otherwise.

# Python program to illustrate the

# use of 'is not' identity operator

x = 5.2

if (type(x) is not int):


print("true")

else:

print("false")

Output:
True
----------------------------------------------------------------------------------------------------------------

9. Python Data Types


Data types are the classification or categorization of data items. Python supports the
following built-in data types.

Scalar Types
• int: Positive or negative whole numbers (without a fractional part) e.g. -10, 10, 456,
4654654.
• float: Any real number with a floating-point representation in which a fractional
component is denoted by a decimal symbol or scientific notation e.g. 1.23,
3.4556789e2.
• complex: A number with a real and imaginary component represented as x + 2y.
• bool: Data with one of two built-in values True or False. Notice that 'T' and 'F' are
capital. true and false are not valid booleans and Python will throw an error for
them.
• None: The None represents the null object in Python. A None is returned by
functions that don't explicitly return a value.

Sequence Type
A sequence is an ordered collection of similar or different data types. Python has the
following built-in sequence data types:

• String: A string value is a collection of one or more characters put in single, double or
triple quotes.
• List: A list object is an ordered collection of one or more data items, not necessarily
of the same type, put in square brackets.
• Tuple: A Tuple object is an ordered collection of one or more data items, not
necessarily of the same type, put in parentheses.
Mapping Type
Dictionary: A dictionary Dict() object is an unordered collection of data in a
key:value pair form. A collection of such pairs is enclosed in curly brackets. For
example: {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}

Set Types
• set: Set is mutable, unordered collection of distinct hashable objects. The set is a
Python implementation of the set in Mathematics. A set object has suitable methods to
perform mathematical set operations like union, intersection, difference, etc.
• frozenset: Frozenset is immutable version of set whose elements are added from other
iterables.

Mutable and Immutable Types


Data objects of the above types are stored in a computer's memory for processing.
Some of these values can be modified during processing, but contents of others can't
be altered once they are created in the memory.

Numbers, strings, and Tuples are immutable, which means their contents can't be
altered after creation.

On the other hand, items in a List or Dictionary object can be modified. It is possible
to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are
mutable objects.

----------------------------------------------------------------------------------------------------------------
10) Momentum is calculated as e = mc2 , where m is the mass of the object and c is its velocity.
Write a program that accepts an object‟s mass (in kilogram) and velocity (in meters per second) and
displays its momentum?

Momentum is calculated as e = mc2

, where m is

the mass of the object and c is its velocity. Write a

program that accepts an object‟s mass (in

kilogram) and velocity (in meters per second) and

displays its momentum?

m=float(input("Enter mass: "))

c=float(input("Enter velocity: "))


e=m*c**2

print("The momentum of the particle is", e)

----------------------------------------------------------------------------------------------------------------

11) Write a program that calculates number of seconds in a day.

(A)→a=int(input('enter the number of days'))

#one day has 24 hours,60 minutes in an hour and 60 seconds in a minute

seconds=a*24*60*60

print('the number of seconds on given number of days is',seconds)

----------------------------------------------------------------------------------------------------------------

(12) Write a program that prompts the user to enter the first name and the last name. Then display
the following message.

Hello firstname lastname

Welcome to Python!

(A)→ a=input('Enter your name: ')

print("Hello",a)

print("Welcome to Python!")

----------------------------------------------------------------------------------------------------------------

13.Write a program to read the address of a user.

Display the result by breaking it in multiple lines?

x=0
y=0
for i in address:
x+=1
if i==",":
if address[y]==' ' and y!=0:
listed=address[y+1:x]
else:
listed=address[y:x]
y=x
print(listed)
l=len(address)
if address[y]==' ':
print(address[y+1:l])
else:
print(address[y:l])
----------------------------------------------------------------------------------------------------------------

14)BITWISE OPERATORS:

In Python, bitwise operators are used to perform bitwise calculations on


integers. The integers are first converted into binary and then bit by bit
operations are performed
TYPES OF BITWISE OPERATORS WITH EXAMPLES:

OPERATOR DESCRIPTION SYNTAX

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

BITWISE AND: Returns 1 if both the bits are 1 else 0.


Example;
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a&b=0=0000(binary)
BITWISE OR: Returns 1 if either of the bit is 1 else 0.
Example;
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a|b=14=1110(binary)
BITWISE NOT: Returns one’s compliement of the number.
Example;
a = 10 = 1010 (Binary)
~a=-11=-1011
BITWISE XOR: Returns 1 if one of the bit is 1 and other is 0 else returns
false.
Example;
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a^b=14=1110
BITWISE RIGHT SHIFT:
Example:
a = 10
a >> 1 = 5
BITWISE LEFT SHIFT:
Example;
a = 5 = 0000 0101
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
----------------------------------------------------------------------------------------------------------------
15)
#TO PRINT AREA OF TRIANGLE USING HERON'S FORMULA
a=int(input('length of one side of the triangle' ))
b=int(input('length of second side of the triangle' ))
c=int(input('length of third side of the triangle' ))
s=(a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**0.5
print('the area of triangle is',area)
----------------------------------------------------------------------------------------------------------------

16) Write a program to calculate the total amount of

money in the piggybank, given the coins of

Rs.100, Rs.50, Rs.20, Rs.10.

Answer: #to find the total amoit of money in a piggy bank,given the coins of rs100,rs50,rs20&rs10

rs100=int(input("enter no.of rs100 coins:" ))


rs50=int(input("enter no.of rs50 coins:" ))

rs20=int(input("enter no.of rs20 coins:" ))

rs10=int(input("enter no.of rs10 coins:"))

total=int

total=100*rs100+50*rs50+20*rs20+10*rs10

print("total money:",total)

----------------------------------------------------------------------------------------------------------------

17)Write the rules for an identifier? Write a program

to print the digit at one‟s place of a number?

(Hint: n=12345, the digit at one‟s place is 5)?

Answer: Rules for an identifier: indentifier can be a combination of letters in lowercase or uppercase
or digits or an underscore_.

-it can't start with a digit.

-keywords can't be used as identifiers

-we can't use special symbols as !,@,#,$,%,etc

-it can be of any length

#program to print the digit at one's place

n=int(input("give me a number:"))

print(n)

u=n%10 #u=number at unit's place

print("the number at unit's place is:",u)

----------------------------------------------------------------------------------------------------------------
18. Write a program to enter a number and display its

hex, octal equivalent and also print its square

root?

import math

n = int(input('Enter a number: '))


print(hex(n)) #converts the given number to corresponding hex code

print(oct(n)) # converts given number into its octal equivalent

print(round(math.sqrt(n),2))

----------------------------------------------------------------------------------------------------------------

19. Write a program that makes use of the following

built-in mathematical functions?

i. abs()

ii. pow()

iii. mean()

iv. max()

v. divmod()

print('''Choose From the following operations:

1. absolute

2. power

3. mean

4. max

5. divmod

''')

import statistics

choice = int(input('Enter your choice: '))

if(choice>0 and choice<6):

if choice == 1:

number = int(input('Enter the number: '))

print(abs(number))
if choice == 2:

number = int(input('Enter number: '))

number2 = int(input('Enter the power: '))

print(pow(number,number2))

if choice == 3:

lst = []

items = int(input('Enter the number of items to be added into list: '))

for i in range(items):

print(f'Enter number{i+1}: ')

item = int(input())

lst.append(item)

print(statistics.mean(lst))

if choice == 4:

number = int(input('Enter number1: '))

number2 = int(input('Enter number2: '))

print(max(number,number2))

if choice == 5:

number = int(input('Enter number: '))

number2 = int(input('Enter divisor: '))

result = divmod(number,number2)

print(f'The quotient is: {result[0]}')

print(f'The remainder is: {result[1]}')

else:

print('Enter a number between 1 and 5.')

----------------------------------------------------------------------------------------------------------------

20. Write a program to perform the following

operations
i. Convert binary '1100001110' into

decimal int

ii. Convert a float value 4.33 into a numeric

string

iii. Obtain integer quotient and remainder

while dividing 29 with 5

iv. Obtain hexadecimal equivalent of

decimal 34567

print(int('1100001110',2))

print(str(4.33))

print(29//5)

print(29%5)

print(hex(34567))

-----------------------------------END OF PART (B)-----------------------------------------------

PART(C):

1) The provided code stub reads two integers from STDIN, a and b, write a Python program to print
three lines where: i. The first line contains the sum of the two numbers. ii. The second line contains
the difference of the two numbers (first - second). iii. The third line contains the product of the two
numbers.
(A)
a=int(input('enter the number' ))
b=int(input('enter the second number'))
(adding of two numbers)
c=a+b
print(c)
(subtracting two numbers)
d=a-b
print(d)
(product of two numbers)
e=a*b
print(e)
----------------------------------------------------------------------------------------------------------------
(2) The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a
list of students. Print the average of the marks array for the student name provided, showing 2
places after the decimal
(A)
n = int(input('Enter the number of values to be added: '))
dict_marks = {}
total = 0
status = 1
average = 0

for _ in range(n):
lst = []
name_marks = input().split()
for items in range(1,len(name_marks)):
lst.append(int(name_marks[items]))
dict_marks.update({name_marks[0].lower() : lst})

choice = input('Enter the name of the student to find average:').lower()

if choice in dict_marks.keys():
student_name = dict_marks[choice]
for item in student_name:
if item>=0 and item<=100:
total += item
else:
print('Marks cannot less than 0 or greater than 100')
status = -1
break
average = total/len(student_name)
else:
print(f"{choice} doesn't exist")
if status == 1:
print("%.2f"%average)
else:
print(f'Program exited with status code {status}')

----------------------------------------------------------------------------------------------------------------

(3) Given the participants' score sheet for your University Sports Day, you are required to find the
runner-up score. You are given n scores. Store them in a list and find the score of the runner-up.

(A)

a=int(input('Enter number of participants: ')) #5

b=[int(x) for x in input().split()] #2 3 6 6 5

n=len(b) #5

b.sort() #2 3 5 6 6

c=set(b) # {2 3 5 6 }

d=list(c) #[ 2 3 5 6]

print(d[n-2]) #5

----------------------------------------------------------------------------------------------------------------

4.You are given a string and your task is to swap

cases. In other words, convert all lowercase letters

to uppercase letters and vice versa.

(A)

a=input()

for i in a:

if i.isupper():

i=i.lower()

print(i, end="")

elif i.islower():

i=i.upper()

print(i, end="")

else:

print(i, end="")
------------------------------------------------------------------------------------------------------------------ --------------------

5.Consider a list (list = []). You can perform the

following commands:

1. insert i e: Insert integer e at position i.

2. print: Print the list.

3. remove e: Delete the first occurrence of

integer e.

4. append e: Insert integer e at the end of the

list.

5. sort: Sort the list.

6. pop: Pop the last element from the list.

7. reverse: Reverse the list.

Initialize your list and read in the value of n

followed by lines of commands where each

command will be of the 7 types listed above.

Iterate through each command in order and

perform the corresponding operation on your list.

(A)

lst = []

n = int(input('Enter the number of operations you want to perform: '))

if n>0:

i =0

while i < n :

choice = input().split()

operation = choice[0].lower()

if operation == 'append':

value = int(choice[1])

lst.append(value)
elif operation == 'insert':

index = int(choice[1])

value = int(choice[2])

lst.insert(index,value)

elif operation == 'pop':

lst.pop()

elif operation == 'print':

print(lst)

elif operation == 'sort':

lst.sort()

elif operation == 'reverse':

lst.reverse()

elif operation == 'remove':

value = int(choice[1])

lst.remove(value)

else:

print('Invalid operation')

i -= 1

i += 1

else:

print('Please enter number > 0')


--------------------------------------END OF SECTION C----------------------------------------------
----------------------------END OF MODULE 1---------------------------------------------------------

PYTHON SOLUTIONS MODULE-2


PART-A

1. Find the output of the following? i, j, k=4, -1, 0

w=i or j or k

x=i and j and k

y=i or j and k

z=i and j or k

print(w,x,y,z)

(A)

OUTPUT:

4 0 4 -1

----------------------------------------------------------------------------------------------------------------------------- ---------

2. Find the output of the following? a = 10 a = not not a print(a)

(A)

OUTPUT:

True

----------------------------------------------------------------------------------------------------------------------------- ---------

3. Find the output of the following?


x, y, z = 20, 40, 45
if x > y and x > z :
print(„biggest =‟+ str(x))
else y > x and y > z :
print(„biggest =‟+ str(y))
else z > x and z > y:
print(„biggest =‟ + str(z))

(A) The above code is wrong as it has conditions after else. However, if we fix it by
replacing else with elif, the output is biggest = 45

--------------------------------------------------------------------------------------------------------------------------------------

4. Find the output of the following?


num = 30
k = 100 if num <=10 else 500
print(k)

(A)

OUTPUT:

500

----------------------------------------------------------------------------------------------------------------------------- ---------

5. Find the output of the following?


a = 10 b =60
if a and b > 20:
print(„Hello‟)
else:
print(„Hi‟)

(A)

OUTPUT:

Hello

----------------------------------------------------------------------------------------------------------------------------- ---------

6. Find the output of the following?


a = 10 b = 60 if a > 20 and b > 20:
print(„Hello‟)
else:
print(„Hi‟)

(A)

OUTPUT:

Hi

----------------------------------------------------------------------------------------------------------------------------- ---------

7. Find the output of the following?


a = 10 if a = 30 or 40 or 60:
print(„Hello‟)
else:
print(„Hi‟)

(A)

OUTPUT:

Hi

----------------------------------------------------------------------------------------------------------------------------- ---------

8. Find the output of the following?


if a = 30
if a == 40 or a == 60:
printf(„Hello‟)
else:
print(„Hi‟)

(A)OUTPUT:

Hi

----------------------------------------------------------------------------------------------------------------------------- ---------

9. Find the output of the following?


a = 10
if a in (30, 40, 50):
print(„Hello‟)
else:
print(„Hi‟)

(A)

OUTPUT:

Hi

----------------------------------------------------------------------------------------------------------------------------- ---------

10. Find the errors if any in the following expression?


a = 12.25 b = 12.52
if a = b :
print(„a and b are equal‟)

(A)It isn’t a=b, as = is an assigning operation. The solution is a==b,which is the equality operator.

----------------------------------------------------------------------------------------------------------------------------- ---------

11) Find the errors if any in the following expression?


if ord(„X‟) < ord(„x‟)
print(„Unicode value of x is smaller than that of x')

The error here is after the if condition there should be a colon or else
it gives you indentation error.
--------------------------------------------------------------------------------------------------------------------------------------

12.Find the errors if any in the following expression?

x = 10 ; y = 15

if x >= 2 then

print(„x‟)

(A)

In case of using ‘if’condition is used there must be colon(:) at the end.

So;the correct output is:-


x = 10
y = 15
if x >= 2:

print('x')
----------------------------------------------------------------------------------------------------------------------------- ---------

(13) Find the errors if any in the following expression?

x = 10 ; y = 15 if x % 2 = y % 3

print(„Carpathians\n‟)

#ERROR

x=10

y=15

if x%2==y%3:

print("yes")

----------------------------------------------------------------------------------------------------------------------------- ---------

(14) Find the errors if any in the following expression?


x, y = 30, 40
if x == y:

print(„x is equal to y‟)

elseif x > y : print(„x is greater than y‟)

elseif x < y : print(„x is less than y‟)

(A)

The error in the code is with decision statements. The above code contains elseif
instead of elif.
----------------------------------------------------------------------------------------------------------------------------- ---------

(15) Write the following code using conditional expression?

x = 3 y = 3.0

if x == y ;

print(„x and y are equal‟)

else :

print(„x and y are not equal‟)

(A)

x=3

y = 3.0

if x == y :

print('x and y are equal')

else :

print('x and y are not equal')

'''

'''

x=3

y = 3.0

result = 'x and y are equal' if x == y else 'x and y are not equal'

print(result)

------------------------------------------------------------------------------------------------------------------------------------ --

16. Explain range() function with example?

(A)
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
range(start, stop, step)

Create a sequence of numbers from 3 to 5, and print each item in the


sequence:

x = range(3, 6)
for n in x:
print(n)
----------------------------------------------------------------------------------------------------------------------------- ---------

17. Explain break and continue statement in Python?

(A)

Break statements exist in Python to exit or “break” a for or while conditional


loop. When the loop ends, the code picks up from and executes the next line
immediately following the loop that was broken.
The continue statement is used to skip code within a loop for certain iterations
of the loop. After the code is skipped, the loop continues where it left off.

--------------------------------------------------------------------------------------------------------------------------------------

18. Write the usage of pass statement with example?

(A)

The pass statement is used as a placeholder for future code. When the pass
statement is executed, nothing happens, but you avoid getting an error when empty
code is not allowed. Empty code is not allowed in loops, function definitions, class
definitions, or in if statements.

--------------------------------------------------------------------------------------------------------------------------------------

19. Write a program to display the numbers from 10 to 1 in descending order?

(A)

for i in range(11,0,-1):

print(i)
----------------------------------------------------------------------------------------------------------------

20. Write a program to display the elements of a list using for loop?

(A)

# Python program to print list

# using for loop

a = [1, 2,3,4,5]

for x in range(len(a)):

print(a[x])

------------------------------------------------------END OF PART A-----------------------------------------------------------

PART-B
1. Explain the decision control statements in Python?
(A)
Python, like many other computer programming languages, uses Boolean logic for its decision
control. That is, the Python interpreter compares one or more values in order to decide whether
to execute a piece of code or not, given the proper syntax and instructions.
Decision control is then divided into two major categories, conditional and repetition. Conditional
logic simply uses the keyword if and a Boolean expression to decide whether or not to execute a
code block. Repetition builds on the conditional constructs by giving us a simple method in which
to repeat a block of code while a Boolean expression evaluates to true.
----------------------------------------------------------------------------------------------------------------------------- ---------

(2) Write a program to determine whether character entered is a vowel or not?

(A)

character = input()

lower_case_character = character.lower()

if len(character)>1:

print('Please enter only a single character')

else:

if lower_case_character == 'a' or lower_case_character == 'e' or lower_case_character == 'i' or


lower_case_character == 'o' or lower_case_character == 'u':

print('Vowel')
else:

print('Consonant')

----------------------------------------------------------------------------------------------------------------------------- ---------

(3) Write a program to find the greatest number from three numbers?

(A)

a=int(input())

b=int(input())

c=int(input())

if a>b and a>c:

print(a)

if b>a and b>c:

print(b)

else:

print(c)

----------------------------------------------------------------------------------------------------------------------------- ---------

(4) Write a program to calculate tax given the following conditions:

i. If income is less than 1,50,000 then no tax.

ii. If taxable income is 1,50,001 – 300,000 then charge 10% tax.

iii. If taxable income is 3,00,001 – 500,000 then charge 20% tax

iv. If taxable income is above 5,00,001 then charge 30% tax.

(A)

a=int(input('Enter income: '))

if a<150000:

print('no tax')

if 150001<a<300000:

print('your tax is ', 0.1*a)

if 300001<a<500000:

print('your tax is ',0.2*a)

if a>500001:
print('your tax is ',0.3*a)

----------------------------------------------------------------------------------------------------------------------------- ---------

(5) Write a program to enter the marks of a student in four subjects. Then calculate the total and
aggregate, and display the grade obtained by the student.

i. If the student scores an aggregate greater than 75%, then the grade is distinction.

ii. If aggregate is 60 >= and <75→first division

iii. If aggregate is 50>= and <60→second division

iv. If aggregate is 40>= and<50→third division

v.else,grade is fail.

(A)

lac=int(input())

bee=int(input())

pp=int(input())

che=int(input())

total=lac+bee+pp+che

agg=(total/400)*100

print(agg)

if agg>75:

print('the grade is distinction')

if 60<=agg<75:

print('grade is first division')

if 50<=agg<60:

print('grade is second division')

if 40<=agg<50:

print('grade is third division')

if agg<40:

print('Fail')

----------------------------------------------------------------------------------------------------------------------------- ---------

(6)Write a program to calculate the roots of a quadratic equation?


--------------------------------------------------------------------------------------------------------------------------------------

7) Explain the different types of loops in Python with example?


(A)
while loop: In while loop we must explicitly increment/decrement the loop variable (if any)
whereas in for, the range function would automatically increment the loop variable.

Syntax:

Inislization

while condition:

statement(s)

increment/decrement

Example:

i=1

while i<6:

print(i)

i+=1

else:

print(‘I is no longer less than 6’)

for loop: It can be used to iterate over a list /string/dictionary or iterate over a range of
numbers.

Syntax:

for element in sequence:

statements

Example:

for x in range(1,5)
print(x)

output;1

Nested for loop:putting one loop inside another loop

Adj=[‘red’,’big’,’tasty’]

Fruits=[‘apple’,’banana’,’cherry’]

for x in adj:

for y in fruits:

print(x,y)

Output:

red apple

red banana

red cherry

big apple

big banana

big cherry

tasty apple

tasty banana

tasty cherry

----------------------------------------------------------------------------------------------------------------------------- ---------

(8) Write a program to read the numbers until -1 is encountered. Also count the negative, positives
and zeros entered by the user.

----------------------------------------------------------------------------------------------------------------------------- ---------
(9) Write a program to calculate the LCM and GCD of two numbers.

(A)

print(gcd)#2

print(int(lcm))#6

a=[int(x) for x in input().split()]# 2 6

fm=[]

for i in range(1,a[0]+1):#(1,3)

if a[0]%i==0:

fm.append(i)#[1,2]

print(fm)

fn=[]

for i in range(1,a[1]+1):#(1,7)

if a[1]%i==0:

fn.append(i)#(1,2,3,6)

print(fn)

cf=[]

for k in fm:

if k in fn:

cf.append(k)#[1,2]

print(cf)

gcd=cf[-1]#2

lcm=(a[0]*a[1])/gcd#2*6/2=6

print(gcd)#2
print(int(lcm))#6

--------------------------------------------------------------------------------------------------------------------------------------

10. Explain break, and continue statement with example?


(A)
BREAK STATEMENT: The break statement in Python terminates the current loop
and resumes execution at the next statement, just like the traditional break found in
C.
The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in
both while and for loops.
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)

CONTINUE STATEMENT:The continue statement in Python returns the control to


the beginning of the while loop. The continue statement rejects all the remaining
statements in the current iteration of the loop and moves the control back to the top
of the loop.
The continue statement can be used in both while and for loops.
for letter in 'Python': # First Example
if letter == 'h':
continue

print 'Current Letter :', letter)


----------------------------------------------------------------------------------------------------------------------------- ---------

11) Write a program to read a number and then calculate the sum of its digits?

(A)

n=int(input())

sum = 0

while (n != 0):

sum = sum + (n % 10)

n = n//10

print(sum)
----------------------------------------------------------------------------------------------------------------------------- ---------

(12) Write a program to calculate the average of first n natural numbers using for loop?

(A) num = int(input('How many numbers: '))

total_sum=0

for n in range(num):

numbers = float(input('Enter number : '))

total_sum += numbers

avg = total_sum/num

print('Average of ', num, ' numbers is :', avg)

----------------------------------------------------------------------------------------------------------------------------- ---------

13. Write a program using for loop to print all the numbers from m to n thereby classifying them as
even or odd?

(A)

m=int(input())

n=int(input())

tem=m

print("even numbers are ", end="")

while m<=n:

if m%2==0:

print(m, end=" ")

m+=2

elif m%2!=0 and m!=n:

print(m+1, end=" ")

m+=2

else:

break

m=tem
print("\nodd numbers are ", end="")

while m<=n:

if m%2!=0:

print(m, end=" ")

m+=2

elif m%2==0 and m!=n:

print(m+1, end=" ")

m+=2

METHOD-2:

m=int(input())

n=int(input())

even=[]

odd=[]

for i in range(m,n+1):

if i%2==0:

even.append(i)

else:

odd.append(i)

print("even numbers are",even)

print("odd numbers are",odd)

METHOD-3:

m=int(input())

n=int(input())

print("even numbers are ", end="")


for i in range(m, n+1):

if i%2==0:

print(i, end=" ")

print("\nodd numbers are ", end="")

for i in range(m, n+1):

if i%2!=0:

print(i, end=" ")

--------------------------------------------------------------------------------------------------------- -----------------------------

14.Write a program to check whether a number is

prime or not?

(A)

a=int(input())

b=1

c=0

while b<(a/2):

b+=1

if a%b==0:

c=1

if a==1:

print("Neither prime nor composite")

elif c==0:

print("Prime Number")

else:

print("Composite Number")

METHOD-2:
a=int(input())

for i in range(2,a):

if a%i==0:

print("it is not a prime")

break

else:

print("it is a prime")

------------------------------------------------------------------------------------------------------------------ --------------------

15.Write a program to find the sum of the series –

1 /2 + 2/3 + …..+ n/(n+1)

(A)

n=int(input())

i=1

tot=0

while i<=n:

x=i+1

y=i/x

tot=tot+y

i+=1

print(tot)
------------------------------------------------------------------------------------------------------------------ --------------------

(16)Write a program to find the sum of the series –1/1 + 2^2/2 + 3^3/3+ …..+ n2/n

(A)

n=int(input())

tot=0

i=1

while i<=n:

x=i**2

y=x/i

tot=tot+y

i+=1

print(tot)

----------------------------------------------------------------------------------------------------------------------------- ---------

(17) Write a program to generate the calendar of a month given the start_day and the number of
days in that month?

----------------------------------------------------------------------------------------------------------------------------- ---------

18.PASS STATEMENT: The pass statement is generally used as a


placeholder i.e. when the user does not know what code to write. So user
simply places pass at that line. Sometimes, pass is used when the user
doesn’t want any code to execute. So user simply places pass there as
empty code is not allowed in loops, function definitions, class definitions,
or in if statements. So using pass statement user avoids this error.
Syntax:
pass
ELSE STATEMENT:An else statement can be combined with an if statement.
An else statement contains the block of code that executes if the conditional
expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only
one else statement following if.
Syntax

The syntax of the if...else statement is −


if expression:
statement(s)
else:
statement(s)

----------------------------------------------------------------------------------------------------------------------------- ---------

19.

Write a program to print the following pattern:

12

345

6789

'''

(A)

n=int(input())

count = 0

for items in range(0,n):

for items2 in range(0,items+1):

print(count, end = ' ')

count +=1

print('')

--------------------------------------------------------------------------------------------------------------------------------------

20.

Write a program to print the following pattern:

22

333

4444

'''

(A) n=int(input())
for i in range(1,n):

for j in range(1,i+1):

print(i,end = ' ')

print('')

----------------------------------------------------------------------------------------------------------------------------- ---------

PART(C)

(1)

Write a Python program to input a number from

user and swap first and last digit of the given

number.

(A)

n = int(input('Enter a number to swap first and last places: '))

lst_num = list(str(n))

swapped_number = 0

last_element_index = len(lst_num) - 1

lst_num[0],lst_num[last_element_index] = lst_num[last_element_index], lst_num[0]

for items in lst_num:

swapped_number = swapped_number * 10 + int(items)

print(swapped_number)

----------------------------------------------------------------------------------------------------------------------------- ---------

(2) Write a Python program to count frequency of digits in a given number.


(A)

a=int(input())

digits=[]

while a>0:

digits.append(a%10)

a=a//10

i=0

while i<10:

frequency=0

for x in digits:

if i==x:

frequency+=1

print(f"The frequency of {i} is {frequency}")

i+=1

----------------------------------------------------------------------------------------------------------------------------- ---------

(3) Python Program to Print Rectangle Star Pattern

(A)

rows = int(input("Please Enter the Total Number of Rows : "))

columns = int(input("Please Enter the Total Number of Columns : "))

print("Rectangle Star Pattern")

for i in range(rows):

for j in range(columns):

print('*', end = ' ')

print()

--------------------------------------------------------------------------------------------------------------------------------------

(4) Write a Python program to print the given number pattern series of 1's and 0's at alternate
columns using loop
(A)

rows = int(input("Enter the total Number of Rows : "))

columns = int(input("Enter the total Number of Columns : "))

for i in range(1, rows + 1):

for j in range(1, columns + 1):

if(j % 2 == 0):

print('0',end='')

else:

print('1',end='')

print()

----------------------------------------------------------------------------------------------------------------------------- ---------

(5) Write a Python program to print inverted right triangle star pattern series using for loop.

(A)

n=int(input())

for i in range(n+1,0,-1):

print('*'*(i-1))

-----------------------------------------------END OF PART(C)----------------------------------------------------------------
------------------------------------------------END OF MODULE 2------------------------------------------------------------

MODULE 3
PARTA
#1

'''Lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(Lst[2:5]) #[3, 4, 5]

print(Lst[::2]) #[1, 3, 5, 7, 9]

print(Lst[1::3]) #[2, 5, 8]

print(Lst[::-1]) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]'''

----------------------------------------------------------------------------------------------------------------------------- ---------
#2

'''Lst1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Lst2 = Lst1

Lst3 = Lst1[2:6]

print(Lst2) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(Lst3) #[3, 4, 5, 6]

print(del Lst1[2:4]) #[1,2,5,6,7,8,9,10]

print(del Lst1)''' #their won’t be a output has we deleted the list

----------------------------------------------------------------------------------------------------------------------------- ---------
#3

'''Lst1 = [6, 3, 7, 0, 1, 2, 4, 9]

print(min(Lst1)) #0

print(sum(Lst1)) #32

print(len(Lst1)) #8

print(all(Lst1)) #False

print(any(Lst1)) #True'''

----------------------------------------------------------------------------------------------------------------------------- ---------

#4

'''Lst1 = [6, 3, 7, 0, 1, 2, 4, 9]

print(Lst1.append(10)) #[6,3,7,0,1,2,4,9,10]

print(Lst1.count(4)) #1

print(Lst1.insert(3, 100)) #[6,3,7,100,0,1,2,4,9]

print(Lst1.pop()) #10'''

----------------------------------------------------------------------------------------------------------------------------- ---------
#5

'''Lst1 = [6, 3, 7, 0, 1, 2, 4, 9]

Lst2 = [6, 7, 8, 9, 10]

print(Lst1.sort()) #[0,1,2,3,4,5,6,7,9]

print(Lst1.extend(Lst2)) #[0,1,2,3,4,6,7,9,6,7,8,9,10]

print(Lst1.reverse()) #[9, 4, 2, 1, 0, 7, 3, 6]

print(Lst1.remove(0)''' #[6, 3, 7, 1, 2, 4, 9]
----------------------------------------------------------------------------------------------------------------------------- ---------
#6

'''cubes = [i**3 for i in range(1, 6)]

print(cubes)''’ #[1, 8, 27, 64, 125]

----------------------------------------------------------------------------------------------------------------------------- ---------
#7

'''T = (1, 2, [3, 4])

T[2][0] = 5

print(T) #(1, 2, [5, 4])'''

--------------------------------------------------------------------------------------------------------------------------------------
#8

'''T1 = 'a', 'bcd', 12.34

T2 = T1, (5, 6, 7, 8)

print(T2) #(('a', 'bcd', 12.34), (5, 6, 7, 8))'''

--------------------------------------------------------------------------------------------------------------------------------------
#9

'''T = (1, 'abc')

L = [1, 'abc']

print(T == L) #false

print(T == tuple(L)) #true

print(list(T) == L) #true'''

--------------------------------------------------------------------------------------------------------------------------------------
#10

'''t = ("abc", "def")

(key, value) = t

print(key, value) #abc def

----------------------------------------------------------------------------------------------------------------------------- ---------

You might also like