NCERT Computer Science Class #11 – Chapter #5 Solutions

Chapter 5 – Getting Started with Python

  1. Which of the following identifier names are invalid and why?

i Serial_no.

ii 1st_Room

iii Hundred$

iv Total Marks

v Total_Marks

vi total-Marks

vii _Percentage

viii True

Summary of Validity

Identifier NameValidityReason
Serial_no.InvalidEnds with a special character (.)
1st_RoomInvalidStarts with a digit
Hundred$InvalidContains an invalid character ($)
Total MarksInvalidContains a space
Total_MarksValidFollows all identifier rules
total-MarksInvalidContains an invalid character (-)
_PercentageValidFollows all identifier rules
TrueInvalidReserved keyword

2. Write the corresponding Python assignment statements:

a) Assign 10 to variable length and 20 to variable breadth.

length = 10
breadth = 20

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

# Calculate the average and assign it to sum
sum = (length + breadth) / 2

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

stationery = ['Paper', 'Gel Pen', 'Eraser']

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

first = 'Mohandas'
middle = 'Karamchand'
last = '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

# Concatenate with spaces
fullname = first + " " + middle + " " + last

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.

# Logical expression
result = (num1 + num2) < 12

# Output the result
print(result)  # This will print: True

b) num3 is not more than 24

# Logical expression 
result = num3 <= 24

c) 6.75 is between the values of integers num1 and num2

# Logical expression 
result = (min(num1, num2) < 6.75 < max(num1, num2))

d) The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.

result = (middle > first) and (middle < last)

e) List Stationery is empty.

result = len(stationery) == 0

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

a) 0 == 1 == 2

0 == (1 == 2)

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

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

c) 1 < -1 == 3 > 4

(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)

NameError: name 'num3' is not defined

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

a) Number of months in a year

The data type used to represent "the number of months in a year" will be ‘int

b) Resident of Delhi or not

The data type used to represent "Resident of Delhi or not" will be 'bool' (Boolean)

c) Mobile number

The data type used to represent "mobile number" will be ‘int

d) Pocket money

The data type used to represent "Pocket Money" will be ‘decimal

e) Volume of a sphere

The data type used to represent "Volume of Sphere" will be ‘float

f) Perimeter of a square

The data type used to represent "Perimeter of Square" will be ‘float

g) Name of the student

The data type used to represent the "name of a student" will be 'str' (string)

h) Address of the student

The data type used to represent the "Address of the Student" will be 'str' (string)

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

a)  num1 += num2 + num3

print (num1)

# output
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((312)-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)

ValueError: invalid literal for int() with base 10: '3.14'

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

Error Type: Runtime Error
Reason: Attempting to divide by zero triggers a ZeroDivisionError exception in Python.

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

Error Type: Runtime Error
Specific Error: ZeroDivisionError
Reason: The division operation attempts to divide by zero, which is mathematically undefined and results in a runtime exception when executed.

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:

To determine if a dart hits the dartboard, we can use the equation of a circle. The equation for a circle centered at the origin (0, 0) with radius r is given by:
x2  +  y2   ≤   r2
In this case, the radius r is 10 units. Therefore, our expression to check if the dart hits the board will be:

x**2 + y**2 <= 10**2

a) (0,0)

x = 0 
y = 0
result = x**2 + y**2  <=  10**2 
# 0 + 0 <= 100 
# result is True

b) (10,10)

result = x**2 + y**2 <= 10**2  
# 100 + 100 <= 100
# result is False

c) (6, 6)

result = x**2 + y**2 <= 10**2 
# 36 + 36 <= 100 
# result is True

d) (7,8)

result = x**2 + y**2 <= 10**2  
# 49 + 64 <= 100
# result is False

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

def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit."""
    fahrenheit = celsius * (9/5) + 32
    return fahrenheit

# Define the boiling and freezing points in Celsius
boiling_point_c = 100  # Boiling point of water in Celsius
freezing_point_c = 0    # Freezing point of water in Celsius

# Convert to Fahrenheit
boiling_point_f = celsius_to_fahrenheit(boiling_point_c)
freezing_point_f = celsius_to_fahrenheit(freezing_point_c)

# Output the results
print(f"Boiling point of water: {boiling_point_f} °F")
print(f"Freezing point of water: {freezing_point_f} °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.

# Input values
P = float(input("Enter the principal amount (P): "))
R = float(input("Enter the rate of interest (R) in % per annum: "))
T = float(input("Enter the time period (T) in years: "))

# Calculate Simple Interest and Total Amount Payable
SI = (P * R * T) / 100
total_amount = P + SI

# Output results
print(f"Simple Interest (SI): {SI:.2f}")
print(f"Total Amount Payable: {total_amount:.2f}")

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.

# Input values
x = float(input("Days A takes: "))
y = float(input("Days B takes: "))
z = float(input("Days C takes: "))

# Calculate days to complete the work together
days_needed = (x * y * z) / (x * y + y * z + x * z)

# Output result
print(f"Days required to complete the work together: {days_needed:.2f} days")

13. Write a program to enter two integers and perform all arithmetic operations on them.

# Input two integers
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))

# Perform arithmetic operations
print(f"\nAddition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b if b != 0 else 'Undefined (division by zero)'}")
print(f"Modulus: {a % b if b != 0 else 'Undefined (modulus by zero)'}")

14. Write a program to swap two numbers using a third variable.

# Input two numbers
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

# Display original values
print(f"\nBefore swapping: a = {a}, b = {b}")

# Swap using a third variable
temp = a
a = b
b = temp

# Display swapped values
print(f"After swapping: a = {a}, b = {b}")

15. Write a program to swap two numbers without using a third variable.

# Input two numbers
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

# Swap without a third variable using arithmetic operations
a = a + b
b = a - b
a = a - b

# Display results
print(f"After swapping: a = {a}, b = {b}")

16. Write a program to repeat the string ‘‘GOOD MORNING” n times. Here ‘n’ is an integer entered by the user.

# Input number of repetitions
n = int(input("Enter the number of times to repeat 'GOOD MORNING': "))

# Repeat the string and display the result
result = "GOOD MORNING " * n
print(result.strip())  # Use strip() to remove the trailing space

17. Write a program to find average of three numbers.

# Input three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Calculate the average
average = (num1 + num2 + num3) / 3

# Output the result
print(f"The average of the three numbers is: {average:.2f}")

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

def sphere_volume(radius):
    """Calculate the volume of a sphere given its radius."""
    return (4/3) * math.pi * (radius ** 3)

# List of radii
radii = [7, 12, 16]

# Calculate and print the volume for each radius
for r in radii:
    volume = sphere_volume(r)
    print(f"The volume of a sphere with radius {r} cm is: {volume:.2f} cubic cm")

19. Write a to enter program their that asks the user name and age. Print a message addressed to the user that tells the user the year in which they will turn 100 years old.

from datetime import datetime

def calculate_year_turn_100(age):
    """Calculate the year when the user will turn 100 years old."""
    current_year = datetime.now().year
    return current_year + (100 - age)

# Get user input
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))

# Calculate the year when the user will turn 100
year_turn_100 = calculate_year_turn_100(age)

# Print the message
print(f"Hello, {name}! You will turn 100 years old in the year {year_turn_100}.")

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.

def calculate_energy(mass):
    """Calculate the energy using the formula E = mc²."""
    c = 3 * 10**8  # Speed of light in meters per second
    return mass * (c ** 2)

# Get user input
mass = float(input("Enter the mass of the object in kilograms: "))

# Calculate energy
energy = calculate_energy(mass)

# Print the result
print(f"The energy equivalent of {mass} kg is {energy:.2e} joules.")

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 calculate_height(length, angle):
    """Calculate the height reached by the ladder on the wall."""
    # Convert angle from degrees to radians
    angle_rad = math.radians(angle)
    return length * math.sin(angle_rad)

# List of (length, angle) tuples
ladder_data = [
    (16, 75),
    (20, 0),
    (24, 45),
    (24, 80)
]

# Calculate and print the heights
for length, angle in ladder_data:
    height = calculate_height(length, angle)
    print(f"The height reached by a {length} feet ladder at {angle} degrees is: {height:.2f} feet.")
Posts created 29

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top