Hi,
In this post i attached my lecture notes - 2 which contains chapter 4 and 5, but in this post i am going to post practice questions and tutorials only for chapter 4
here is the lecture notes
In this chapter you will learn,
- if statement
- if-else statement
- if -elif -else statement
- nested if statement
programming exercises
You can find these exercise questions at the end of the chapter 4 in the book that i attached above, here i have written answers for each questions in exercises. So, you can check with your answers
1. Roman Numerals
Write a program that prompts the user to enter a number within the range of 1 through 10.The program should display the Roman numeral version of that number. If the number is outside the range of 1 through 10, the program should display an error message. The following table shows the Roman numerals for the numbers 1 through 10:
Number Roman Numeral1 I
2 II
3 III
4 IV
5 V
6 VI
7 VII
8 VIII
9 IX
10 X
answer :-
number = int(input("Enter the number between 1 and 10 : "))
if number == 1:
print("Roman version of "+str(number) + " is : "+ "I" )
elif number == 2:
print("Roman version of "+str(number) + " is : "+ "II" )
elif number == 3:
print("Roman version of "+str(number) + " is : "+ "III" )
elif number == 4:
print("Roman version of "+str(number) + " is : "+ "IV" )
elif number == 5:
print("Roman version of "+str(number) + " is : "+ "V" )
elif number == 6:
print("Roman version of "+str(number) + " is : "+ "VI" )
elif number == 7:
print("Roman version of "+str(number) + " is : "+ "VII" )
elif number == 8:
print("Roman version of "+str(number) + " is : "+ "VIII" )
elif number == 9:
print("Roman version of "+str(number) + " is : "+ "IX" )
elif number == 10:
print("Roman version of "+str(number) + " is : "+ "X" )
else:
print("you have entered outside range of 1 to 10")
2. Areas of Rectangles
The area of a rectangle is the rectangle’s length times its width. Write a program that asks for the length and width of two rectangles. The program should tell the user which rectangle has the greater area, or if the areas are the same.
answer :-
length1 = int(input("Enter the length of rectangle 1 : "))
width1 = int(input("Enter the width of rectangle 1 : "))
length2 = int(input("Enter the length of rectangle 2 : "))
width2 = int(input("Enter the width of rectangle 2 : "))
areaRactangle1 = length1 * width1
areaRactangle2 = length2 * width2
print("area of Ractangle1 :",areaRactangle1)
print("area of Ractangle2 :",areaRactangle2)
if areaRactangle1 == areaRactangle2:
print("area of Ractangle1 and Ractangle2 are equal.... " )
elif areaRactangle1 > areaRactangle2:
print("Ractangle1 has greater area than Ractangle2" )
else:
print("Ractangle2 has greater area than Ractangle1")
3. Mass and Weight
Scientists measure an object’s mass in kilograms and its weight in newtons. If you know the amount of mass of an object in kilograms, you can calculate its weight in newtons with the following formula:
weight = mass * 9.8
Write a program that asks the user to enter an object’s mass, and then calculates its weight. If the object weighs more than 1,000 newtons, display a message indicating that it is too heavy. If the object weighs less than 10 newtons, display a message indicating that it is too light.
answer :-
objectMass = float(input("Enter the object's mass (kg) : "))
weigtht = objectMass * 9.8
if weigtht > 1000:
print("this is too heavy " )
elif weigtht < 10:
print("this is too light " )
The date June 10, 1960, is special because when it is written in the following format, the month times the day equals the year:
6/10/60
Design a program that asks the user to enter a month (in numeric form), a day, and a two digit year. The program should then determine whether the month times the day equals the year. If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.
answer :-
month = int(input("Enter the month (in numeric form ) : "))
day = int(input("Enter the day of the month : "))
year = int(input("Enter the last two digits of the year : "))
monthTimesDay = month * day
if monthTimesDay == year:
print("the date that you have entered is magic " )
else:
print("the date that you haven't entered is magic")
The colors red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors. When you mix two primary colors, you get a secondary color, as shown here:
When you mix red and blue, you get purple.
When you mix red and yellow, you get orange.
When you mix blue and yellow, you get green.
Design a program that prompts the user to enter the names of two primary colors to mix. If the user enters anything other than “red,” “blue,” or “yellow,” the program should display an error message. Otherwise, the program should display the name of the secondary color that results.
answer :-
color1 = input("Enter the name of color among red , blue , yellow : ")
color2 = input("Enter the name of color among red , blue , yellow : ")
if color1 == "red" and color2 == "blue" or \
color1 == "blue" and color2 == "red":
print("when you mix "+color1+" and "+color2+ \
", you will get secondary color : purple" )
elif color1 == "red" and color2 == "yellow" or \
color1 == "yellow" and color2 == "red":
print("when you mix "+color1+" and "+color2+ \
", you will get secondary color : orange" )
elif color1 == "blue" and color2 == "yellow" or \
color1 == "yellow" and color2 == "blue":
print("when you mix "+color1+" and "+color2+ \
", you will get secondary color : green" )
else:
print("you have entered incorrect primary colors")
6. Change for a Dollar Game
Create a change-counting game that gets the user to enter the number of coins required to make exactly one dollar. The program should prompt the user to enter the number of pennies, nickels, dimes, and quarters. If the total value of the coins entered is equal to one dollar, the program should congratulate the user for winning the game. Otherwise, the program should display a message indicating whether the amount entered was more than or less than one dollar.
answer :-
noOfPennies = int(input("Enter the name of PENNIES : "))
noOfNickels = int(input("Enter the name of NICKELS : "))
noOfDimes = int(input("Enter the name of DIMES : "))
noOfQuarters = int(input("Enter the name of QUARTERS : "))
ONEDOLLAR = 1.00
PENNY = 0.01
NICKEL = 0.05
DIME = 0.10
QUARTER = 0.25
pennyWorth = noOfPennies * PENNY
nickelWorth = noOfNickels * NICKEL
dimeWorth = noOfDimes * DIME
quarterWorth = noOfQuarters * QUARTER
totalWorth = pennyWorth + nickelWorth + dimeWorth + quarterWorth
if totalWorth < ONEDOLLAR:
print("oops ! amount that you entered is less than one dollar" )
elif totalWorth == ONEDOLLAR:
print("congratulation ! you won the game" )
elif totalWorth > ONEDOLLAR:
print("oops ! amount that you entered is more than one dollar" )
7. Book Club Points
Serendipity Booksellers has a book club that awards points to its customers based on the number of books purchased each month. The points are awarded as follows:
• If a customer purchases 0 books, he or she earns 0 points.
• If a customer purchases 1 book, he or she earns 5 points.
• If a customer purchases 2 books, he or she earns 15 points.
• If a customer purchases 3 books, he or she earns 30 points.
• If a customer purchases 4 or more books, he or she earns 60 points.
Write a program that asks the user to enter the number of books that he or she has purchased this month and displays the number of points awarded.
answer :-
numberOfbooks = int(input("Enter the number of books "+\
"that you have purchased : "))
if numberOfbooks == 0:
print("you have earns 0 points" )
elif numberOfbooks == 1:
print("you have earns 5 points" )
elif numberOfbooks == 2:
print("you have earns 15 points" )
elif numberOfbooks == 3:
print("you have earns 30 points" )
elif numberOfbooks >= 4:
print("you have earns 60 points" )
8. Software Sales
A software company sells a package that retails for $99. Quantity discounts are given according to the following table:
Quantity Discount
10–19 20%
20–49 30%
50–99 40%
100 or more 50%
Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total amount of the purchase after the discount.
answer :-
"that you have purchased : "))
if 10 <= numberOfPackages and numberOfPackages < 20:
print("price of a package is :$99")
totalPurhaseAmount = numberOfPackages * 99
totaldiscount = totalPurhaseAmount * .20
totalAmount = totalPurhaseAmount - totaldiscount
print("total Purhase Amount : $"+str(format(totalPurhaseAmount , ',d')))
print("total discount : $"+str(format(totaldiscount , ',.2f')))
print("total Purhase Amount after deduct discount : $"+ \
str(format(totalAmount , ',.2f')))
elif 20 <= numberOfPackages and numberOfPackages < 50:
print("price of a package is :$99")
totalPurhaseAmount = numberOfPackages * 99
totaldiscount = totalPurhaseAmount * .20
totalAmount = totalPurhaseAmount - totaldiscount
print("total Purhase Amount : $"+str(format(totalPurhaseAmount , ',d')))
print("total discount : $"+str(format(totaldiscount , ',.2f')))
print("total Purhase Amount after deduct discount : $"+ \
str(format(totalAmount , ',.2f')))
elif 50 <= numberOfPackages and numberOfPackages < 100:
print("price of a package is :$99")
totalPurhaseAmount = numberOfPackages * 99
totaldiscount = totalPurhaseAmount * .20
totalAmount = totalPurhaseAmount - totaldiscount
print("total Purhase Amount : $"+str(format(totalPurhaseAmount , ',d')))
print("total discount : $"+str(format(totaldiscount , ',.2f')))
print("total Purhase Amount after deduct discount : $"+ \
str(format(totalAmount , ',.2f')))
elif numberOfPackages >= 100:
print("price of a package is :$99")
totalPurhaseAmount = numberOfPackages * 99
totaldiscount = totalPurhaseAmount * .20
totalAmount = totalPurhaseAmount - totaldiscount
print("total Purhase Amount : $"+str(format(totalPurhaseAmount , ',d')))
print("total discount : $"+str(format(totaldiscount , ',.2f')))
print("total Purhase Amount after deduct discount : $"+ \
str(format(totalAmount , ',.2f')))
9. Shipping Charges
The Fast Freight Shipping Company charges the following rates:
Weight of Package Rate per Pound
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80
Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
answer :-
weightOfPackage = float(input("Enter the weight of a package : "))
if weightOfPackage <= 2:
print("Rate per pound = $1.10" )
shippingCharge = weightOfPackage * 1.10
print("shipping Charge : $"+str(format(shippingCharge , ',.2f')))
elif 2 < weightOfPackage and weightOfPackage <= 6:
print("Rate per pound = $2.20" )
shippingCharge = weightOfPackage * 2.20
print("shipping Charge : $"+str(format(shippingCharge , ',.2f')))
elif 6 < weightOfPackage and weightOfPackage <= 10:
print("Rate per pound = $3.70" )
shippingCharge = weightOfPackage * 3.70
print("shipping Charge : $"+str(format(shippingCharge , ',.2f')))
elif weightOfPackage > 10:
print("Rate per pound = $3.80" )
shippingCharge = weightOfPackage * 3.80
print("shipping Charge : $"+str(format(shippingCharge , ',.2f')))
10. Body Mass Index Program Enhancement
In programming Exercise #6 in Chapter 3 you were asked to write a program that calculates a person’s body mass index (BMI). Recall from that exercise that the BMI is often used to determine whether a person is overweight or underweight for their height. A person’s BMI is calculated with the formula
BMI = weight * 703 / height * height
where weightis measured in pounds and heightis measured in inches. Enhance the program so it displays a message indicating whether the person has optimal weight, is underweight, or is overweight. A person’s weight is considered to be optimal if his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered to be underweight. If the BMI value is greater than 25, the person is considered to be overweight.
answer :-
weight = float(input("Enter the weight(in pounds) : "))
height = float(input("Enter the height(in inches) : "))
BMI = weight * 703 / (height * height)
print("BMI =",format(BMI , ',.2f'))
if 18.5 > BMI :
print("your weight is considered to be underweight " )
elif 18.5 <= BMI and BMI <= 25:
print("your weight is considered to be optimal " )
elif BMI > 25:
print("your weight is considered to be overweight " )
11. Time Calculator
Write a program that asks the user to enter a number of seconds, and works as follows:
• There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds.
• There are 3,600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to 3,600, the program should display the number of hours in that many seconds.
• There are 86,400 seconds in a day. If the number of seconds entered by the user is greater than or equal to 86,400, the program should display the number of days in that many seconds.
answer :-
seconds = int(input("Enter the number of seconds : "))
if seconds < 60:
print("seconds :",seconds)
elif seconds >= 60 and seconds < 3600:
minutes = seconds // 60
print("number of minutes :",minutes)
elif seconds >= 3600 and seconds < 86400:
hours = seconds // 3600
#optional
minutes = (seconds // 60 ) % 60
seconds = seconds % 60
print("number of hours :",hours)
print("number of minutes :",minutes)
print("number of seconds :",seconds)
elif seconds >= 86400:
days = seconds // 86400
#optional
hours = (seconds // 3600) % 24
minutes = (seconds // 60 ) % 60
seconds = seconds % 60
print("number of days :",days)
print("number of hours :",hours)
print("number of minutes :",minutes)
print("number of seconds :",seconds)
from the tutorial,
1. The if statement
A.prompts the user to
enter three test scores, calculates the average score and displays a message of
congratulations if the average score is greater than or equal to 85.
answer :-
test1 = float(input("Enter the test1's score : "))
test2 = float(input("Enter the test2's score : "))
test3 = float(input("Enter the test3's score : "))
average = (test1 + test2 + test3) / 3
print(format(average ,'.2f'))
if average >= 85:
print("Congratulatons!!")
else:
print("Better luck next time!!")
B.Modify the program above such that before getting the scores from the user,
the program prompts the user for the student name and then student id and
after calculating the average score it displays a report which includes the
student name and id, the average score and the congratulations message if
appropriate.
answer :-
sName = input("Enter the name of student : ")
sId = input("Enter the student ID : ")
test1 = int(input("Enter the test1's score : "))
test2 = int(input("Enter the test2's score : "))
test3 = int(input("Enter the test3's score : "))
average = (test1 + test2 + test3) / 3
print(format(average ,'.2f'))
if average >= 85:
print("dear" , sName , "and student ID",sId,"Congratulatons!!")
else:
print("Better luck next time!!")
2.The if-else statement
A.prompts the user to
enter a password and tests the validity of the password.
answer :-
password = input("Enter the password : ")if password == 'prospero':
print("password accepted!")
else:
print("sorry,incorrect password")
B.Modify the program above such that before asking for the password, it asks for
a username and only prompts for the password if the username is correct. If
the username is incorrect the program should terminate with an invalid
username message only. For simplicity, in this exercise, assume that the
correct username is the string tne60003 and the password is as in the previous
exercise.
username = input("Enter the username : ")
if username == 'tne60003':
password = input("Enter the password")
print("your password is : ",password)
else:
print("sorry,incorrect username")
3.The if-elif-else statement
A.Dr. Suarez teaches a literature class and uses the following 10 point grading scale for all of his exams:
Test Score Grade
80 and above HD
70–79 D
60–69 C
50–59 P
Below 50 F
answer :-
#constants for the grates
HD = 80
D = 70
C = 60
P = 50
marks = int(input("Enter the mark : "))
if marks >= HD:
print("Your grade is HD")
elif marks >= D:
print("Your grade is D")
elif marks >= C:
print("Your grade is C")
elif marks >= P:
print("Your grade is pass")
else:
print("You fail")
He has asked you to write a program that will allow a student to enter a test score and then display the grade for that score
B.Modify the program above such that it checks that the score is within the valid
range (ie. 0-100 inclusive) before attempting to determine the grade. The
program should terminate with an invalid score message if the given test score
is outside the acceptable range
answer :-
#constants for the gratesHD = 80
D = 70
C = 60
P = 50
marks = int(input("Enter the mark : "))
if marks >= HD and marks <= 100:
print("HD")
elif marks >= D and marks < HD:
print("D")
elif marks >= C and marks < D:
print("C")
elif marks >= P and marks < C:
print("pass")
elif marks >= 0 and marks < P:
print("fail")
else:
print("unacceptable")
or
mark = int(input("Enter your mark : "))
while(0 > mark or mark > 100):
print("Error::invalid maarks")mark = int(input("Enter your mark : "))
A = 80
B = 60
C = 50
if(mark >= A):
print("A")
elif (mark >= B):
print("B")
elif(mark >= C):
print("C")
else:
print("you fail")
i will post chapter 5 very soon. any correction has to be made, you can make it as comments it will be appreciated.
No comments:
Post a Comment