0% found this document useful (0 votes)
20 views31 pages

Python Practical File

Uploaded by

shikha kaushic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views31 pages

Python Practical File

Uploaded by

shikha kaushic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

PYTHON

CH-6 Getting started with python.

Question 1:
Which of the following identifier names are invalid and why?
i Serial_no. v Total_Marks
ii 1st_Room vi total-Marks
iii Hundred$ vii _Percentage
iv Total Marks viii True

ANSWER:

i) Serial_no.: Invalid - Identifier in python cannot contain any special character except
underscore(_).

ii) 1st_Room: Invalid - Identifier in Python cannot start with a number.

iii) Hundred$: Invalid - Identifier in Python cannot contain any special character except
underscore(_).

iv) Total Marks: Invalid - Identifier in Python cannot contain any special character
except underscore (_). If more than one word is used as a variable then it can be
separated using underscore (_), instead of space.

v) Total_Marks: Valid

vi) total-Marks: Invalid - Identifier in Python cannot contain any special character except
underscore (_). If more than one word is used as a variable then it can be separated
using underscore (_), instead of a hyphen (- ).

vii) _Percentage: Valid

viii) True: Invalid - Identifier in Python should not be a reserved keyword.

Question 2:
Write the corresponding Python assignment statements:
a) Assign 10 to variable length and 20 to variable breadth.

b) Assign the average of values of variables length and breadth to a variable sum

c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable
stationery.

d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first,


middle and last.

e) Assign the concatenated value of string variables first, middle and last to
variable full name. Make sure to incorporate blank spaces appropriately between
different parts of names.
ANSWER:

a) length, breadth = 10,20

b) sum = (length + breadth)/2

c) stationary = ['Paper’, ‘Gel Pen’, ‘Eraser']

d) first,middle,last = "Mohandas","Karamchand","Gandhi"

e) fullname = first +" "+ middle +" "+ last

Question 4:
Add a pair of parentheses to each expression so that it evaluates to True.

a) 0 == 1 == 2

b) 2 + 3 == 4 + 5 == 7

c) 1 < -1 == 3 > 4
ANSWER:

a) ( 0 == (1==2))

b) (2 + (3 == 4) + 5) == 7

c) (1 < -1) == (3 > 4 )

Question 5:
Write the output of the following.

a) num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)

b) num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)

c) num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
ANSWER:

a) 2, 5

b) 6, 4

c) Error as num3 is used in RHS of line 2 (num3, num2 = num1, num3 + 1) before
defining it earlier.

Question 6:
Which data type will be used to represent the following data values and why?

a) Number of months in a year

b) Resident of Delhi or not

c) Mobile number

d) Pocket money

e) Volume of a sphere

f) Perimeter of a square

g) Name of the student

h) Address of the student


ANSWER:
a) The int data type will be used to represent 'Number of months in a year' as it will be
an integer i.e. 12.

b) The Boolean data type will be used to represent 'Resident of Delhi or not' as a person
will be either a resident of Delhi or not a resident of Delhi. Therefore, the values True or
False will be sufficient to represent the values.

c) The integer data type will be used to represent 'Mobile number' as it will be a ten-digit
integer only.

d) The float data type will be used to represent 'Pocket money' as it can be in decimal.
e.g. Rs. 250.50 i.e. 250 rupees and 50 paise.

e) The float data type will be used to represent 'Volume of a sphere'.


The formula for the volume of a sphere:
Volume of sphere, V=43πr3
Even if 'r' is a whole number, the value of volume can be a fraction which can be
represented in a decimal form easily by float data type.

f) The float data type will be used to represent 'Perimeter of a square'.


The perimeter of a square:
Perimeter = 4 × side length
If the side length is a decimal number, the result may come out to be a decimal number
which can be easily represented by float data type.

Note:- If the side length is a whole number, the perimeter will always be an integer,
however, we should be open to the possibility that the side length can be in decimal as
well.

g) The string data type will be used to represent 'Name of the student'.

h)The string data type will be used to represent 'Address of the student'. However, if we
must store the address in a more structured format, we can use dictionary data type as
well. e.g. Address = { 'Line1': ‘Address line 1', 'Line2':'Address
Line2', 'Locality’: ‘Locality Name', 'City’: ‘City Name',
'Pincode':110001, 'Country’: ‘India'}

Question 7:
Give the output of the following when num1 = 4, num2 = 3, num3 = 2

a) num1 += num2 + num3


print (num1)
b) num1 = num1 ** (num2 + num3)
print (num1)

c) num1 **= num2 + num3

d) num1 = '5' + '5'


print(num1)

e) print(4.00/(2.0+2.0))

f) num1 = 2+9*((3*12)-8)/10
print(num1)

g) num1 = 24 // 4 // 2
print(num1)

h) num1 = float(10)
print (num1)

i) num1 = int('3.14')
print (num1)

j) print('Bye' == 'BYE')

k) print(10 != 9 and 20 >= 20)

l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29>= 29/9)

m) print(5 % 10 + 10 < 50 and 29 <= 29)

n) print((0 < 6) or (not (10 == 6) and (10<0)))


ANSWER:

a) num1 += 3 + 2
The above statement can be written as
num1 = num1 + 3 + 2 = 4 + 3 + 2 = 9
Therefore, print(num1) will give the output 9.

b) num1 = num1 ** (num2 + num3)


The above statement will be executed as per the following steps.
num1 = 4 ** (3 + 5) = 4 ** 5 = 1024
Therefore, print(num1) will give the output 1024.

c) num1 **= num2 + num3


The above statement can be written as
num1 **= 5
num1 = num1 ** 5
num1 = 4 ** 5
num1 = 1024
Therefore, the output will be 1024.

d) num1 = '5' + '5'


The RHS in the above statement is '5' + '5'. Please note that 5 is enclosed in
quotes and hence will be treated as a string. Therefore, the first line is just a string
concatenation which will give the output 55. The type of output will be a string, not an
integer.

e) print(4.00/(2.0 + 2.0))
The numbers written in the statement are in float data type therefore, the output will be
also in float data type.
print(4.00/(2.0 + 2.0))
print(4.0/4.0)
1.0
Therefore, the output will be 1.0.

f) num1 = 2 + 9 * ((3 * 12) - 8) /10


# The expression within inner brackets will be evaluated first
num1 = 2 + 9 * (36 - 8) /10
# The expression within outer brackets will be evaluated next
num1 = 2 + 9 * 28/10
# * and / are of same precedence, hence, left to right order is followed
num1 = 2 + 252/10
num1 = 2 + 25.2
num1 = 27.2
Therefore, the output will be 27.2.

g) num1 = 24 // 4 // 2
#When the operators are same, left to right order will be followed for operation
num1 = 6 // 2
#When floor division is used, return value will be int data type
num1 = 3
Therefore, the output will be 3

h) num1 = float(10)
float(10) will convert integer value to float value and therefore, the output will be
10.0.

i) num1 = int('3.14')
This will result in an error as we cannot pass string representation of float to an int
function.
j) print('Bye' == 'BYE')
As Python compares string character to character and when different characters are
found then their Unicode value is compared. The character with lower Unicode value is
considered to be smaller. Here, 'y' has Unicode 121 and 'Y' has 89. Therefore, the
output will be 'False'.

k) print(10 != 9 and 20 >= 20)


print(True and True)
print(True)
Therefore, the output will be 'True'.

l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29>= 29/9)


Taking the above statement in two separate parts

LHS:
10 + 6 * 2 ** 2 != 9//4 - 3
10 + 6 * 4 != 2 - 3
10 + 24 != -1
34 != -1
True

RHS:
29 >= 29/9
True

Now the complete equation can be written as


print(True and True)
Therefore, the output will be 'True'.

m) print(5 % 10 + 10 < 50 and 29 <= 29)


Taking the above statement in two separate parts

LHS :
5 % 10 + 10 < 50
5 + 10 < 50
15 < 50
True

RHS:
29 <= 29
True

Now, the complete equation can be written as


print(True and True)
Therefore, the output will be 'True'.
n) print( (0 < 6) or (not (10 == 6) and (10<0) ) )
print(True or (not False and False))
print(True or (True and False))
# not will be evaluated before and/or.
print(True or False)
print(True)
Therefore, the output will be 'True'.

Question 8:
Categorise the following as syntax error, logical error, or runtime error:

a) 25 / 0

b) num1 = 25; num2 = 0; num1 / num2


ANSWER:

a) Runtime Error. The syntax for the division is correct. The error will arise only when
'interpreter' will run this line.

b) Runtime Error. The syntax is correct. The error will arise only when 'interpreter' will
run the line containing these statements.

Question 10:
Write a Python program to convert temperature in degree Celsius to degree
Fahrenheit. If water boils at 100 degree C and freezes as 0 degree C, use the
program to find out what is the boiling point and freezing point of water on the
Fahrenheit scale. (Hint: T(°F) = T(°C) × 9/5 + 32)
ANSWER:

Program:
#defining the boiling and freezing temp in celcius
boil = 100
freeze = 0
print('Water Boiling temperature in Fahrenheit::')
#Calculating Boiling temperature in Fahrenheit
tb = boil * (9/5) + 32
#Printing the temperature
print(tb)
print('Water Freezing temperature in Fahrenheit::')
#Calculating Boiling temperature in Fahrenheit
tf = freeze * (9/5) + 32
#Printing the temperature
print(tf)

OUTPUT:
Water Boiling temperature in Fahrenheit::
212.0
Water Freezing temperature in Fahrenheit::
32.0

Question 11:

Write a Python program to calculate the amount payable if money has been lent on
simple interest.
Principal or money lent = P, Rate of interest = R% per annum and Time = T years. Then
Simple Interest (SI) = (P x R x T)/ 100.
Amount payable = Principal + SI. P, R and T are given as input to the program.
ANSWER:

Program:

#Asking the user for Principal, rate of interest and time


P = float(input('Enter the principal: '))
R = float(input('Enter the rate of interest per annum: '))
T = float(input('Enter the time in years: '))
#calculating simple interest
SI = (P * R * T)/100
#caculating amount = Simple Interest + Principal
amount = SI + P
#Printing the total amount
print('Total amount:’, amount)

OUTPUT:-
Enter the principal: 12500
Enter the rate of interest per annum: 4.5
Enter the time in years: 4
Total amount: 14750.0

Question 12:
Write a program to calculate in how many days a work will be completed by three
persons A, B and C together. A, B, C take x days, y days and z days respectively
to do the job alone. The formula to calculate the number of days if they work
together is xyz/(xy + yz + xz) days where x, y, and z are given as input to the
program.
ANSWER:

Program:

#Asking for the number of days taken by A, B, C to complete the


work alone
x = int(input('Enter the number of days required by A to complete
work alone: '))
y = int(input('Enter the number of days required by B to complete
work alone: '))
z = int(input('Enter the number of days required by C to complete
work alone: '))

#calculating the time if all three person work together


#formula used as per the question
combined = (x * y * z)/(x*y + y*z + x*z)
#rounding the answer to 2 decimal places for easy readability
days = round(combined,2)
#printing the total time taken by all three persons
print('Total time taken to complete work if A, B and C work
together: ', days)

OUTPUT:-
Enter the number of days required by A to complete work alone: 8
Enter the number of days required by B to complete work alone: 10
Enter the number of days required by C to complete work alone: 20
Total time taken to complete work if A, B and C work together:
3.64

Question 18:
The volume of a sphere with radius r is 4/3πr3. Write a Python program to find the
volume of spheres with radius 7 cm, 12 cm, 16 cm, respectively.
ANSWER:

Program:
#defining three different radius using variables r1, r2, r3
r1 = 7
r2 = 12
r3 = 16
#calculating the volume using the formula
volume1 = (4/3*22/7*r1**3)
volume2 = (4/3*22/7*r2**3)
volume3 = (4/3*22/7*r3**3)

#printing the volume after using the round function to two


decimal place for better readability

print("When the radius is",r1,"cm, the volume of the sphere will


be", round(volume1,2),"cc")
print("When the radius is",r2,"cm, the volume of the sphere will
be", round(volume2,2),"cc")
print("When the radius is",r3,"cm, the volume of the sphere will
be", round(volume3,2),"cc")

OUTPUT:
When the radius is 7 cm, the volume of the sphere will be 1437.33 cc
When the radius is 12 cm, the volume of the sphere will be 7241.14 cc
When the radius is 16 cm, the volume of the sphere will be 17164.19 cc

CH-7 Python fundamentals


Question 1
Write a program that displays a joke. But display the
punchline only when the user presses enter key.
(Hint. You may use input( ))

Solution

print("Why is 6 afraid of 7?")


input("Press Enter")
print("Because 7 8(ate) 9 :-)")

Output

Why is 6 afraid of 7?
Press Enter
Because 7 8(ate) 9 :-)

Question 2
Write a program to read today's date (only del part) from
user. Then display how many days are left in the current
month.

Solution

day = int(input("Enter day part of today's date: "))


totalDays = int(input("Enter total number of days in this
month: "))
daysLeft = totalDays - day
print(daysLeft, "days are left in current month")

Output

Enter day part of today's date: 16


Enter total number of days in this month: 31
15 days are left in current month.

Question 3
Write a program that generates the following output :
5
10
9
Assign value 5 to a variable using assignment operator (=)
Multiply it with 2 to generate 10 and subtract 1 to generate
9.

Solution

a = 5
print(a)
a = a * 2
print(a)
a = a - 1
print(a)

Output

5
10
9

Question 4
Modify above program to print output as 5@10@9.
Solution

a = 5
print(a, end='@')
a = a * 2
print(a, end='@')
a = a - 1
print(a)

Output

5@10@9

Question 5
Write the program with maximum three lines of code and
that assigns first 5 multiples of a number to 5 variables and
then print them.

Solution

a = int(input("Enter a number: "))


b, c, d, e = a * 2, a * 3, a * 4, a * 5
print(a, b, c, d, e)

Output

Enter a number: 2
2 4 6 8 10

Question 6
Write a Python program that accepts radius of a circle and
prints its area.

Solution

r = float(input("Enter radius of circle: "))


a = 3.14159 * r * r
print("Area of circle =", a)

Output

Enter radius of circle: 7.5


Area of circle = 176.7144375

Question 7
Write Python program that accepts marks in 5 subjects and
outputs average marks.

Solution

m1 = int(input("Enter first subject marks: "))


m2 = int(input("Enter second subject marks: "))
m3 = int(input("Enter third subject marks: "))
m4 = int(input("Enter fourth subject marks: "))
m5 = int(input("Enter fifth subject marks: "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
print("Average Marks =", avg)

Output

Enter first subject marks: 65


Enter second subject marks: 78
Enter third subject marks: 79
Enter fourth subject marks: 80
Enter fifth subject marks: 85
Average Marks = 77.4

Question 8
Write a short program that asks for your height in
centimetres and then converts your height to feet and
inches. (1 foot = 12 inches, 1 inch = 2.54 cm).

Solution

ht = int(input("Enter your height in centimetres: "))


htInInch = ht / 2.54;
feet = htInInch // 12;
inch = htInInch % 12;
print("Your height is", feet, "feet and", inch, "inches")

Output

Enter your height in centimetres: 162


Your height is 5.0 feet and 3.7795275590551185 inches.

Question 9
Write a program to read a number n and print n 2, n3 and n4.
Solution

n = int(input("Enter n: "))
n2, n3, n4 = n ** 2, n ** 3, n ** 4
print("n =", n)
print("n^2 =", n2)
print("n^3 =", n3)
print("n^4 =", n4)

Output

Enter n: 2
n = 2
n^2 = 4
n^3 = 8
n^4 = 16

Question 10
Write a program to find area of a triangle.

Solution

h = float(input("Enter height of the triangle: "))


b = float(input("Enter base of the triangle: "))
area = 0.5 * b * h
print("Area of triangle = ", area)

Output

Enter height of the triangle: 2.5


Enter base of the triangle: 5
Area of triangle = 6.25

Question 11
Write a program to compute simple interest and compound
interest.

Solution

p = float(input("Enter principal: "))


r = float(input("Enter rate: "))
t = int(input("Enter time: "))
si = (p * r * t) / 100
ci = p * ((1 + (r / 100 ))** t) - p
print("Simple interest = ", si)
print("Compound interest = ", ci)
Output

Enter principal: 15217.75


Enter rate: 9.2
Enter time: 3
Simple interest = 4200.098999999999
Compound interest = 4598.357987312007

Question 12
Write a program to input a number and print its first five
multiples.

Solution

n = int(input("Enter number: "))


print("First five multiples of", n, "are")
print(n, n * 2, n * 3, n * 4, n * 5)

Output

Enter number: 5.
First five multiples of 5 are.
5 10 15 20 25

Question 13
Write a program to read details like name, class, age of a
student and then print the details firstly in same line and
then in separate lines. Make sure to have two blank lines in
these two different types of prints.

Solution

n = input("Enter name of student: ")


c = int(input("Enter class of student: "))
a = int(input("Enter age of student: "))
print("Name:", n, "Class:", c, "Age:", a)
print()
print()
print("Name:", n)
print("Class:", c)
print("Age:", a)

Output

Enter name of student: Kavya


Enter class of student: 11
Enter age of student: 17
Name: Kavya Class: 11 Age: 17

Name: Kavya
Class: 11
Age: 17

Question 14
Write a program to input a single digit(n) and print a 3-digit
number created as <n(n + 1)(n + 2)> e.g., if you input 7,
then it should print 789. Assume that the input digit is in
range 1-7.

Solution

d = int(input("Enter a digit in range 1-7: "))


n = d * 10 + d + 1
n = n * 10 + d + 2
print("3-digit number =", n)

Output

Enter a digit in range 1-7: 7.


3-digit number = 789

Question 15
Write a program to read three numbers in three variables
and swap first two variables with the sums of first and
second, second and third numbers respectively.

Solution

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("The three number are", a, b, c)
a, b = a + b, b + c
print("Numbers after swapping are", a, b, c)

Output

Enter first number: 10.


Enter second number: 15.
Enter third number: 20.
The three number are 10 15 20.
Numbers after swapping are 25 35 20.

CH-8 Data Handling


Question 1
Write a program to obtain temperatures of 7 days (Monday,
Tuesday ... Sunday) and then display average temperature
of the week.

Solution

d1 = float(input("Enter Sunday Temperature: "))


d2 = float(input("Enter Monday Temperature: "))
d3 = float(input("Enter Tuesday Temperature: "))
d4 = float(input("Enter Wednesday Temperature: "))
d5 = float(input("Enter Thursday Temperature: "))
d6 = float(input("Enter Friday Temperature: "))
d7 = float(input("Enter Saturday Temperature: "))

avg = (d1 + d2 + d3 + d4 + d5 + d6 + d7) / 7

print("Average Temperature =", avg)

Output

Enter Sunday Temperature: 21.6


Enter Monday Temperature: 22.3
Enter Tuesday Temperature: 24.5
Enter Wednesday Temperature: 23.0
Enter Thursday Temperature: 23.7
Enter Friday Temperature: 24.2
Enter Saturday Temperature: 25
Average Temperature = 23.47142857142857

Question 2
Write a program to obtain x, y, z from user and calculate
expression : 4x4 + 3y3 + 9z + 6π

Solution

import math

x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))

res = 4 * x ** 4 + 3 * y ** 3 + 9 * z + 6 * math.pi

print("Result =", res)

Output

Enter x: 2
Enter y: 3
Enter z: 5
Result = 208.84955592153875

Question 3
Write a program that reads a number of seconds and prints
it in form : mins and seconds, e.g., 200 seconds are printed
as 3 mins and 20 seconds.
[Hint. use // and % to get minutes and seconds]

Solution

totalSecs = int(input("Enter seconds: "))

mins = totalSecs // 60
secs = totalSecs % 60

print(mins, "minutes and", secs, "seconds")

Output

Enter seconds: 200


3 minutes and 20 seconds

Question 4
Write a program to take year as input and check if it is a
leap year or not.

Solution

y = int(input("Enter year to check: "))


print(y % 4 and "Not a Leap Year" or "Leap Year")
Output

Enter year to check: 2020


Leap Year

Question 5
Write a program to take two numbers and print if the first
number is fully divisible by second number or not.

Solution

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))
print(x % y and "Not Fully Divisible" or "Fully Divisible")

Output

Enter first number: 4


Enter second number: 2
Fully Divisible

Question 7
Write a program to take a 2-digit number and then print the
reversed number. That is, if the input given is 25, the
program should print 52.

Solution

x = int(input("Enter a two-digit number: "))


y = x % 10 * 10 + x // 10
print("Reversed Number:", y)

Output

Enter a two-digit number: 25


Reversed Number: 52

Question 8
Try writing program (similar to previous one) for three-digit
number i.e., if you input 123, the program should print 321.

Solution

x = int(input("Enter a three-digit number: "))


d1 = x % 10
x //= 10
d2 = x % 10
x //= 10
d3 = x % 10
y = d1 * 100 + d2 * 10 + d3

print("Reversed Number:", y)

Output

Enter a three-digit number: 123


Reversed Number: 321

Question 9
Write a program to take two inputs for day, month and then
calculate which day of the year, the given date is. For
simplicity, take 30 days for all months. For example, if you
give input as: Day3, Month2 then it should print "Day of the
year : 33".

Solution

d = int(input("Enter day: "))


m = int(input("Enter month: "))

n = (m - 1) * 30 + d

print("Day of the year:", n)

Output

Enter day: 3
Enter month: 2
Day of the year: 33

Question 10
Write a program that asks a user for several years, and then
prints out the number of days, hours, minutes, and seconds
in that number of years.
How many years? 10
10.0 years is:
3650.0 days
87600.0 hours
5256000.0 minutes
315360000.0 seconds

Solution

y = float(input("How many years? "))

d = y * 365
h = d * 24
m = h * 60
s = m * 60

print(y, "years is:")


print(d, "days")
print(h, "hours")
print(m, "minutes")
print(s, "seconds")

Output

How many years? 10


10.0 years is:
3650.0 days
87600.0 hours
5256000.0 minutes
315360000.0 seconds

Question 11
Write a program that inputs an age and print age after 10
years as shown below:
What is your age? 17
In ten years, you will be 27 years old!

Solution

a = int(input("What is your age? "))


print("In ten years, you will be", a + 10, "years old!")

Output

What is your age? 17


In ten years, you will be 27 years old!
Question 12
Write a program whose three sample runs are shown below:
Sample Run 1:
Random number between 0 and 5 (A) : 2
Random number between 0 and 5 (B) :5.
A to the power B = 32
Sample Run 2:
Random number between 0 and 5 (A) : 4
Random number between 0 and 5 (B) :3.
A to the power B = 64
Sample Run 3:
Random number between 0 and 5 (A) : 1
Random number between 0 and 5 (B) :1.
A to the power B = 1

Solution

import random

a = random.randint(0, 5)
b = random.randint(0, 5)
c = a ** b

print("Random number between 0 and 5 (A) :", a)


print("Random number between 0 and 5 (B) :", b)
print("A to the power B =", c)

Output

Random number between 0 and 5 (A) : 5


Random number between 0 and 5 (B) : 3
A to the power B = 125

Question 13
Write a program that generates six random numbers in a
sequence created with (start, stop, step). Then print the
mean, median and mode of the generated numbers.

Solution

import random
import statistics

start = int(input("Enter start: "))


stop = int(input("Enter stop: "))
step = int(input("Enter step: "))

a = random.randrange(start, stop, step)


b = random.randrange(start, stop, step)
c = random.randrange(start, stop, step)
d = random.randrange(start, stop, step)
e = random.randrange(start, stop, step)
f = random.randrange(start, stop, step)

print("Generated Numbers:")
print(a, b, c, d, e, f)

seq = (a, b, c, d, e, f)

mean = statistics.mean(seq)
median = statistics.median(seq)
mode = statistics.mode(seq)

print("Mean =", mean)


print("Median =", median)
print("Mode =", mode)

Output

Enter start: 100


Enter stop: 500
Enter step: 5
Generated Numbers:
235 255 320 475 170 325
Mean = 296.6666666666667
Median = 287.5
Mode = 235

CH-9 & 10 String & list manipulation.

Question 1
Write a program to count the number of times a character
occurs in the given string.
Solution

str = input("Enter the string: ")


ch = input("Enter the character to count: ");
c = str.count(ch)
print(ch, "occurs", c, "times")

Output

Enter the string: KnowledgeBoat


Enter the character to count: e
e occurs 2 times

Question 2
Write a program which replaces all vowels in the string with
'*'.

Solution

str = input("Enter the string: ")


newStr = ""
for ch in str :
lch = ch.lower()
if lch == 'a' \
or lch == 'e' \
or lch == 'i' \
or lch == 'o' \
or lch == 'u' :
newStr += '*'
else :
newStr += ch
print(newStr)

Output

Enter the string: Computer Studies


C*mp*t*r St*d**s

Question 3
Write a program which reverses a string and stores the
reversed string in a new string.

Solution

str = input("Enter the string: ")


newStr = ""
for ch in str :
newStr = ch + newStr
print(newStr)

Output

Enter the string: computer studies


seiduts retupmoc

Question 4
Write a program to increment the elements of a list with a
number.

Solution

lst = eval(input("Enter a list: "))


print("Existing list is:", lst)

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

for i in range(len(lst)):
lst[i] += n

print("List after increment:", lst)

Output

Enter a list: [1, 2, 3, 4, 5]


Existing list is: [1, 2, 3, 4, 5]
Enter a number: 10
List after increment: [11, 12, 13, 14, 15]

Question 5
Write a program that reverses a list of integers (in place).

Solution

l = eval(input("Enter a list: "))


print("Original list:", l)
l.reverse()
print("Reversed list:", l)
Output

Enter a list: [1, 2, 3, 4, 5]


Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]

Question 6
Write a program that inputs two lists and creates a third,
that contains all elements of the first followed by all
elements of the second.

Solution

l1 = eval(input("Enter first list: "))


l2 = eval(input("Enter second list: "))
l3 = l1 + l2
print("Joined List:", l3)

Output

Enter first list: [1, 2, 3, 4, 5]


Enter second list: [11, 12, 13, 14, 15]
Joined List: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]

Question 7
Create a function addNumbers(x) that takes a number as an
argument and adds all the integers between 1 and the
number (inclusive) and returns the total number.
Answer:
def add Numbers (num):
total = 0
i = 1
while i< = num:
total + = i
i+ = 1
return total

Question 8
Create a function addNumbers(start, end) that adds all the
integers between the start and end value (inclusive) and
returns the total sum.
Answer:
def addNumbers(start, end):
total = 0
i = start
while start < = end:
total + = start
start + = 1
return total

Question 9
Create a function countPages(x) that takes the number of pages of a book
as an argument and counts the number of times the digit ‘1’ appears in
the page number.
Answer:
def countPages(num):
total = 0
i = 1
while i<=num:
page_no = str(i)
total + = page_no.count(‘1’)
i+ = l
return total

Database & SQL


1. Match the following clauses with their respective functions.

ALTER Insert the values in a table

UPDATE Restrictions on columns

DELETE Table definition

INSERT INTO Change the name of a column

CONSTRAINTS Update existing information in a table

DESC Delete an existing row from a table


CREATE Create a database

. Choose appropriate answer with respect to the following code


snippet.

CREATE TABLE student (

name CHAR(30),

student_id INT,

gender CHAR(1),

PRIMARY KEY (student_id)

);

a) What will be the degree of student table?


i) 30
ii) 1
iii) 3
iv) 4

Ans. iii) 3

b) What does ‘name’ represent in the above code snippet?


i) a table
ii) a row
iii) a column
iv) a database

Ans. iii) a column

c) What is true about the following SQL statement?


SelecT * fROM student;
i) Displays contents of table ‘student’
ii) Displays column names and contents of table ‘student’
iii) Results in error as improper case has been used
iv) Displays only the column names of table ‘student’

Ans.: ii) Displays column names and contents of table ‘student’


d) What will be the output of following query?
INSERT INTO student
VALUES (“Suhana”,109,’F’),
VALUES (“Rivaan”,102,’M’),
VALUES (“Atharv”,103,’M’),
VALUES (“Rishika”,105,’F’),
VALUES (“Garvit”,104,’M’),
VALUES (“Shaurya”,109,’M’);
i) Error
ii) No Error
iii) Depends on compiler
iv) Successful completion of the query

Ans.: i) Error

e) In the following query how many rows will be deleted?


DELETE student
WHERE student_id=109;
i) 1 row
ii) All the rows where student ID is equal to 109

iii) No row will be deleted


iv) 2 rows

Ans.: ii) All the rows where student ID is equal to 109

3. Fill in the blanks:

a) ___________ declares that an index in one table is related to that in


another table.
i) Primary Key
ii) Foreign Key
iii) Composite Key
iv) Secondary Key

Ans.: Primary Key

b) The symbol Asterisk (*) in a select query retrieves __.

i) All data from the table

ii) Data of primary key only

iii) NULL data

iv) None of the mentioned


Ans. i) All data from the table

You might also like