The Programming Project

Saturday, October 2, 2021

CBSE CLASS XI CHAPTER 5: GETTING STARTED WITH PYTHON

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.

length = 10
breadth = 20

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

firstVariableinput("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.

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

                            



               

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 9 SOLVED

 

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 9

Programming for school students ( upper to middle/secondary school)

A tech number has even number of digits. If the number is split in two equal halves, then the square of the sum of these halves is equal to the number itself. Write a program to generate and print all four digits tech numbers.



JAVA CODE

public class ISCJava{
       public static void main(String[] args) {
       final int j = 2;
       int counter;
       int lastTwoDigit;
       int firstTwoDigit;
       int temp;
       forint i = 1000 ; i < 10000 ; i++) { // looping through all 4-digits
              counter = 0;
              lastTwoDigit = 0;
              firstTwoDigit = 0;
              temp = i;
              // extracting the last two digit
              while ( counter < j) {
                     lastTwoDigit += (temp%10)*(int)Math.pow(10,counter);
                     counter++;
                     temp /= 10;
                     }
              // extracting the first two digit
              counter = 0;
              while ( counter < j) {
                     firstTwoDigit += (temp%10)*(int)Math.pow(10,counter);
                     counter++;
                     temp /= 10;
                     }
              ifi ==  (int)Math.pow(firstTwoDigit+lastTwoDigit,2))
                     System.out.println(i+" is a tech number.");
              }
       }
}

PYHTON CODE
#PROGRAM TO PRINT ALL 4 DIGITS TECH NUMBER
j = 2
for i in range(9000): #total number of 4 digits number are 9000
    counter = 0
    lastTwoDigit = 0
    firstTwoDigit = 0
    temp = i+1000
    numb = temp
    #extracting the last two digit
    while counter < j:
        lastTwoDigit += int(temp%10*int((10**counter)))
        temp /= 10
        temp = int(temp)
        counter +=1
    #extracting the last two digit
    counter = 0
    while counter < j:
        firstTwoDigit += int(temp%10*int((10**counter)))
        temp /= 10
        temp = int(temp)
        counter +=1
    #print(firstTwoDigit,"last",lastTwoDigit,numb)
    if numb == int((firstTwoDigit+lastTwoDigit)**2):
        print(numb," is a tech number.")

Friday, October 1, 2021

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 8 SOLVED

 

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 8

Programming for school students ( upper to middle/secondary school)

Write a program to input s sentence and convert it into uppercase and display the total number of words starting with letter 'A'.

Example:

INPUT: Advancement and application of Information Technology are ever changing.

OUTPUT: ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER CHANGING.

Number of word(s)starting with A is/are: 4




JAVA CODE

import java.util.Scanner;
public class ISCJava{
       public static void main(String[] args) {
       String sentence;
       int counterStartingA = 0;
       Scanner in = new Scanner(System.in);
       System.out.println("Enter your sentence:");
       sentence = in.nextLine();
       System.out.println();
       System.out.println("OUTPUT:");
       System.out.println("ORIGINAL STATEMENT:");
       System.out.println(sentence);
       System.out.println();
       System.out.println("AFTER CHANGING TO UPPER CASE:");
       for(int i =0isentence.length();i++) {
              char c = sentence.charAt(i);
              if(c >= 'a' && c <= 'z') {
                     c -= 32;
                     System.out.print(c);
              }
              else
              System.out.print(c);   
       }
       //counting number of words staring with A
       System.out.println();
       for(int i =0isentence.length(); i++) 
              if (sentence.charAt(i) == 'A' || sentence.charAt(i) == 'a') {
                     if(i==0)
                            counterStartingA++; 
                     else if(sentence.charAt(i-1) == ' ')
                            counterStartingA++;
              }
       System.out.println("Number of word(s)starting with A is/are: "+counterStartingA);
       in.close();
       }
}


PYTHON CODE

counterStartingA = 0
sentence = str(input("Enter the sentence: "))
print("OUTPUT:")
print("ORIGINAL STATEMENT:")
print(sentence)
print("AFTER CHANGING TO UPPER CASE:")
for i in range(len(sentence)):
    c = (sentence[i])
    if (c >= 'a' and c <= 'z'):
        t = ord(c) -32
        print(chr(t),end="")
    else:
        print(c,end="")
for i in range(len(sentence)):
    if sentence[i] == 'A' or sentence[i] == 'a':
        if i == 0:
            counterStartingA +=1
        elif sentence[i-1] == ' ':
            counterStartingA +=1
print()
print("Number of word(s)starting with A is/are:",counterStartingA)

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 7 SOLVED

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 7

Programming for school students ( upper to middle/secondary school)

Design a class to overload a function series() as follows:

(a) void series (int x, int n) - To display the sum of the series given below:

x+x2+x3+........+xn

(b) void series (int p) - To display the following series:

0, 7, 26, 63, ........ upto p terms

(c) void series () - To display the sum of the series given below

&frac12 + 1⁄3 +&frac14 +.......+1⁄10


import java.util.Scanner;
public class ISCJava{
       public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       Series obj = new Series();
       int choice;
       System.out.println("Enter your choice(1/2/3):");
       choice = in.nextInt();
       switch(choice){
              case 1:
              int xn;
              System.out.println("Enter the value of x:");
              x = in.nextInt();
              System.out.println("Enter the value of n:");
              n = in.nextInt();
              obj.series(x,n);
              break;
              case 2:
              int p;
              System.out.println("Enter the value of p:");
              p = in.nextInt();
              obj.series(p);
              break;
              case 3:
              obj.series();
              break;
              default:
              System.out.println("Wrong Choice:");
       }
       in.close();
       }
}
class Series {
       public void series(int xint n) {
              for (int i = 1; i<= n ;i++)
                     sumOfSeries += Math.pow((double)x,(double)i);
              System.out.println("Sum of the series is:"+sumOfSeries);
       }
       public void series(int p) {
              System.out.println("The series is");
              for(int i = 1; i<= p; i++)
                     if (i != p)
                            System.out.print((int)Math.pow(i, 3)-1+",");
                     else
                            System.out.println((int)Math.pow(i, 3)-1);       
       }
       public void series() {
              for (int i = 2; i<= 10 ;i++)
                     sumOfSeries += (1.0/i);
              System.out.println("Sum of the series is:"+sumOfSeries);
       }
       Series() {
              this.sumOfSeries = 0.0;
       }
       private double sumOfSeries;
}
       
PYTHON CODE
Note: Function overloading is not available in Python.

class Series:
    def seriesOne(self,x,n):
        for i in range(n):
            i +=1
            self.__sumOfSeries += x**i
        print("Sum of the series is:",self.__sumOfSeries)
    def seriesTwo(self,p):
        for i in range(p):
            i +=1
            if i<p:
                print(i**3-1end =",")
            else:
                print(i**3-1end =" ")
    def seriesThree(self):
        for i in range(9):
            i +=2
            self.__sumOfSeries += (1.0/(i+1))
        print("Sum of the series is:",self.__sumOfSeries)
    def __init__(self):
       self.__sumOfSeries = 0
    __sumOfSeries = float(0)
# main program    
obj = Series()
try:
    N = int(input("Enter your choice(1/2/3):"))
    if N > 3:
        print("Your choice in invalid")   
    elif N==1:
        x = int(input("Enter the value of x:"))
        n = int(input("Enter the value of n:"))
        obj.seriesOne(x,n)
    elif N==2:
        p = int(input("Enter the value of p:"))
        obj.seriesTwo(p
    else:
        obj.seriesThree()    
except ValueError as e:
    print("Your choice is invalid")