CBSE CLASS XI CHAPTER 5: GETTING STARTED WITH PYTHON - SOLVED
Summary
• Python is an open-source, high level, interpreter based language that can be used for a multitude of scientific and non-scientific computing purposes.
• Comments are non-executable statements in a program.
• An identifier is a user defined name given to a variable or a constant in a program.
• The process of identifying and removing errors from a computer program is called debugging.
• Trying to use a variable that has not been assigned a value gives an error.
• There are several data types in Python — integer, boolean, float, complex, string, list, tuple, sets, None and dictionary.
Exercise
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: Invalid identifiers are: 1st_Room, Hundred$, Total Marks and True.
Reason: 1st_Room: identifier name cannot start with a digit
Hundred$: Cannot use special character '$'
Total Marks: space is not allowed between two words
True: it is a keyword
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.
sum = (length+breadth)/2
c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable stationery.
stationary = ["Paper","Gel Pen","Eraser"]
d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first, middle and last.
first = 'Mohandas'
second = 'Karamchand'
third = 'Gandhi'
e) Assign the concatenated value of string variables first, middle and last to variable fullname. Make sure to incorporate blank spaces appropriately between different parts of names.
fullname =first+' '+second+' '+third
3. Write logical expressions corresponding to the following statements in Python and evaluate the expressions (assuming variables num1, num2, num3,first, middle, last are already having meaningful values):
a) The sum of 20 and –10 is less than 12.
num1 = 10
num2 = -20
num3 = 12
print(num1 + num2 < num3)
b) num3 is not more than 24.
print(num3 < 24)
c) 6.75 is between the values of integers num1 and num2.
print(num1 < 6.75 and 6.75 < num2)
d) The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.print( middle > first and middle < last)
e) List Stationery is empty.
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
5. Write the output of the following:
a) num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
2 5
b) num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
6 4
c) num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
2 13 2
6. Which data type will be used to represent the following data values and why?
a) Number of months in a year - int - always takes integral value
b) Resident of Delhi or not - bool - binary
c) Mobile number - int - always takes integral value
d) Pocket money - float -
e) Volume of a sphere - float
f) Perimeter of a square - float
g) Name of the student - str
h) Address of the student - str
7. Give the output of the following when num1 = 4, num2 = 3, num3 = 2
a) num1 += num2 + num3
print (num1)
9
b) num1 = num1 ** (num2 + num3)
print (num1)
1024
c) num1 **= num2 + num3
1024
d) num1 = '5' + '5'
print(num1)
55
e) print(4.00/(2.0+2.0))
1.0
f) num1 = 2+9*((3*12)-8)/10
print(num1)
27.2
g) num1 = 24 // 4 // 2
print(num1)
3
h) num1 = float(10)
print (num1)
10.0
i) num1 = int('3.14')
print (num1)
3
j) print('Bye' == 'BYE')
False
k) print(10 != 9 and 20 >= 20)
True
l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29 >= 29/9)
True
m) print(5 % 10 + 10 < 50 and 29 <= 29)
True
n) print((0 < 6) or (not(10 == 6) and (10<0)))
True
8. Categorise the following as syntax error, logical error or runtime error:
a) 25 / 0 runtime error
b) num1 = 25; num2 = 0; num1/num2 logical error
9. A dartboard of radius 10 units and the wall it is hanging on are represented using a two-dimensional
coordinate system, with the board’s center at coordinate (0,0). Variables x and y store the
x-coordinate and the y-coordinate of a dart that hits the dartboard. Write a Python expression using
variables x and y that evaluates to True if the dart hits (is within) the dartboard, and then evaluate the
expression for these dart coordinates:
a) (0,0)
b) (10,10)
c) (6, 6)
d) (7,8)
Expression: (x**2+y**2)**(1/2) <= 10
PYTHON CODE
x = float(input("Enter the x co-ordinate:"))
y = float(input("Enter the y co-ordinate:"))
d = (x**2+y**2)**(1/2) # distance of the point from the origin
if (d <= 10):
print("The dart hits the board.")
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)
degreeCelsius = float(input("Enter the temperature in Celsius:"))
degreeFahrenheit = (degreeCelsius*9)/5 +32
print("Corresponding value in Fahrenheit is", degreeFahrenheit)
freezingTemp = (0*9)/5 +32
print("Water freezes at", freezingTemp," degree F")
boilingTemp = (100*9)/5 +32
print("Water boils at", boilingTemp," degree F")
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.
principal = float(input("Enter the principal or money lent:"))
rateOfInterest = float(input("Enter the rate of interest p.a:"))
time = float(input("Enter the time in years:"))
simpleInterest = (principal*rateOfInterest*time)/100
amount = principal + simpleInterest
print("Amount after %.1f years is %.2f" %(time,amount))
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.
x = float(input("Number of days taken by A to complete the work:"))
y = float(input("Number of days taken by B to complete the work:"))
z = float(input("Number of days taken by C to complete the work:"))
timeRequiredWorkingTogether = (x*y*z)/(x*y+y*z+z*x)
print("Time required working together =",timeRequiredWorkingTogether)
13. Write a program to enter two integers and perform all arithmetic operations on them.
x = float(input("Enter the first number:"))
y = float(input("Enter the second number:"))
print("Sum",x+y)
print("Difference (x-y)",x+y)
print("Product",x*y)
if y != 0:
print("Division (x/y)",x/y)
elif x != 0:
print("Division (y/x)",y/x)
else:
print("Cannot Divide")
if x!= 0 and y!=0:
print("Power (x to the power y",x**y)
if x > 0 and x!=1 and y>0:
print ("Logarithm base x of y is : ", end="")
print (math.log(y,x))
else:
print ("Logarithm base x of y is not defined:")
14. Write a program to swap two numbers using a third variable.
firstVariable= input("Enter the first variable(x):")
secondVariable = input("Enter the second variable(y):")
print("Before Swapping")
print("The first variable is(x)=",firstVariable)
print("The second variable is(y)=",secondVariable)
#swapping
thirdVariable = firstVariable
firstVariable = secondVariable
secondVariable = thirdVariable
print("After Swapping")
print("The first variable is(x)=",firstVariable)
print("The second variable is(y)=",secondVariable)
15. Write a program to swap two numbers without using a third variable.
firstVariable= int(input("Enter the first variable(x):"))
secondVariable = int(input("Enter the second variable(y):"))
print("Before Swapping")
print("The first variable is(x)=",firstVariable)
print("The second variable is(y)=",secondVariable)
#swapping
firstVariable = firstVariable + secondVariable
secondVariable = firstVariable - secondVariable
firstVariable = firstVariable - secondVariable
print("After Swapping")
print("The first variable is(x)=",firstVariable)
print("The second variable is(y)=",secondVariable)
16. Write a program to repeat the string ‘‘GOOD MORNING” n times.
n = int(input("Enter the value of n:"))
messageDisplay = "GOOD MORNING"
for i in range(n):
print(messageDisplay)
if users enter values different from positive integers:
try:
n = int(input("Enter the value of n:"))
messageDisplay = "GOOD MORNING"
if n <= 0:
print("Enter a positive integer:")
for i in range(n):
print(messageDisplay)
except ValueError as e:
print("You must enter an integer:")
17. Write a program to find average of three numbers.
numbOne =float(input("Enter the first number:"))
numbTwo =float(input("Enter the second number:"))
numbThree =float(input("Enter the third number:"))
average = (numbOne+numbTwo+numbThree)/3
print("Average of the numbers is", average)
# Program for finding average on N numbers
numberList = []
N = int(input("How many numbers?"))
for i in range(N):
print("Enter the number at position",i+1,":",end="")
numberList.append(float(input()))
sumOfNumbers = 0
for i in range(N):
sumOfNumbers += numberList[i]
print("Average of the numbers is", sumOfNumbers/N)
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 7cm, 12cm, 16cm, respectively.
import math
radius =float(input("Enter the radius of the sphere:"))
volumeOfSphere = (4*math.pi*radius**3)/3
print("Volume of the sphere is:",round(volumeOfSphere,3))
Using functions:
import math
def VolumeOfSphere(radius):
volumeOfSphere = (4*math.pi*radius**3)/3
print("Volume of the sphere with radius",radius," cm is:",round(volumeOfSphere,3))
radius =float(input("Enter the radius of the sphere:"))
VolumeOfSphere(radius)
VolumeOfSphere(7)
VolumeOfSphere(12)
VolumeOfSphere(16)
19. Write a program that asks the user to enter their name and age. Print a
message addressed to the user that tells the user the year in which they will turn 100 years old.
nameOfUser =str(input("Enter your name:"))
currentYear = int(input("Enter the current year:"))
print("Enter your age as of",currentYear,end=":")
ageOfUser = int(input())
if ageOfUser == 100:
print("Congratulations!", nameOfUser,"you have reached a milestone")
else:
while ageOfUser < 100:
ageOfUser +=1
currentYear +=1
print(nameOfUser,"you will turn 100 in the year",currentYear,"!")
20. The formula E = mc2 states that the equivalent energy (E) can be calculated as the
mass (m) multiplied by the speed of light (c = about 3×108 m/s) squared.
Write a program that accepts the mass of an object and determines its energy.
massOfObject = float(input("Enter the mass in kg:"))
energyEquivalentToMass = massOfObject*(3*10**8)**2
print("Energy of the object is %10.2E" %(energyEquivalentToMass),"J")
21. Presume that a ladder is put upright against a wall. Let variables length and angle store
the length of the ladder and the angle that it forms with the ground as it leans against
the wall. Write a Python program to compute the height reached by the ladder on the
wall for the following values of length and angle:
a) 16 feet and 75 degrees
b) 20 feet and 0 degrees
c) 24 feet and 45 degrees
d) 24 feet and 80 degrees
import math
def heightReachedByLadder(angle,lengthOfLadder):
print("Height reached by the ladder on the wall",round(lengthOfLadder*math.sin(angle),3),"m")
lengthOfLadder = float(input("Enter the length of the ladder in meters:"))
angle = float(input("Enter the angle amde by the ladder with the horizontal in degrees:"))
#converting to radian then using the value
heightReachedByLadder((angle*math.pi)/180,lengthOfLadder)
Case Study-based Question
Schools use “Student Management Information System” (SMIS) to manage student-related data. This system
provides facilities for: • recording and maintaining personal details of students.
• maintaining marks scored in assessments and computing results of students.
• keeping track of student attendance.
• managing many other student-related data.
Let us automate this process step by step. Identify the personal details of students from your
school identity card and write a program to accept these details for all students of your school and display them
in the following format.
numberOfStudents = int(input("Enter the total number of students in the school:"))
recordList = []
schoolName = "The CPROJECTT"
for i in range(numberOfStudents):
recordList.append(str(input("Enter the name of the student:")))
recordList.append(str(input("Enter the roll number of the student:")))
recordList.append(str(input("Enter the class of the student(Roman numerals):")))
recordList.append(str(input("Enter the section of the student(A/B/C/D):")))
recordList.append(str(input("Enter the address of the student:")))
recordList.append(str(input("Enter the city name:")))
recordList.append(str(input("Enter the pin code:")))
recordList.append(str(input("Enter the Parent's/Guardian's contact number:")))
print()
for i in range(numberOfStudents):
print("Name of School",schoolName)
print("Student Name:",recordList[i+0],end =" ")
print("Roll No:",recordList[i+1])
print("Class:",recordList[i+2],end =" ")
print("Section:",recordList[i+3])
print("Address:",recordList[i+4])
print("City:",recordList[i+5],end =" ")
print("Pincode:",recordList[i+6])
print("Parent's/Guardian Contact Number:",recordList[i+7])
No comments:
Post a Comment