Assignment
SUBMITTED TO SUBMITTED BY
Prof.Anshul Verma Name – Shubham Vishwakarma
Roll No. – 23BME058
(Discipline – Mechanical engineering)
Chapter 1 - Introduction to Computers and
Programming
Q 1 how can print 'This is a test of the Python interpreter in python ?
Solution
print('This is a test of the Python interpreter.')
Q 2 Use what you’ve learned about the binary numbering system in
this chapter to convert the
following decimal numbers to binary ?
Solution
print (bin(11))
print (bin(65))
print (bin(100))
print (bin(255))
Q 3 Use what you’ve learned about the binary numbering system in
this chapter to convert the
following binary numbers to decimal:
Solution
(a)
binary = '1101'
decimal = int(binary,2)
print (decimal)
(b)
binary = '1000'
decimal = int(binary,2)
print (decimal)
(c)
binary = '101011'
decimal = int(binary,2)
print (decimal)
Chapter 2 – Input, Processing and output
Q1 Personal Information
Write a program that displays the following information:
Your name
Your address, with city, state, and ZIP
Your telephone number
Your college major
Solution
name = ("Shubham Vishwakarma")
Address = ('''Umaria,Madhya pradesh,484551''')
Number = (9165846809)
college_Major = ("Mechanical Engineering")
print(name)
print(Address)
print(Number)
print(college_Major)
Q2 Sales Prediction
A company has determined that its annual profit is typically 23 percent
of total sales. Write a
program that asks the user to enter the projected amount of total
sales, then displays the profit
that will be made from that amount
Solution
projectedtotalsale = float(input("enter the projected amount of total sales: "))
profit = projectedtotalsale * .23
print("the profit is: ", profit)
Q 3 Land Calculation
One acre of land is equivalent to 43,560 square feet. Write a program
that asks the user to enter
the total square feet in a tract of land and calculates the number of
acres in the tract.
Hint: Divide the amount entered by 43,560 to get the number of acres.
Solution
a = float(input("Enter Total Square Feet in a tract of land : "))
b = a / 43560
print("The tract of land is ", b, "acres")
Q 4 Total Purchase
A customer in a store is purchasing five items. Write a program that
asks for the price of each
item, then displays the subtotal of the sale, the amount of sales tax,
and the total. Assume the
sales tax is 7 percent.
Solution
item1 = float(input("enter item 1 amount here: "))
item2 = float(input("enter item 2 amount here: "))
item3 = float(input("enter item 3 amount here: "))
item4 = float(input("enter item 4 amount here: "))
item5 = float(input("enter item 5 amount here: "))
total = item1 + item2 + item3 + item4 + item5
print("the total is: ", total)
sales_tax = total * .07
print("the sales tax is: ", sales_tax)
total_cost = total + sales_tax
print("the total cost is: ", total_cost)
Q 5 Distance Traveled
Assuming there are no accidents or delays, the distance that a car
travels down the interstate can
be calculated with the following formula:
Distance=Speed×Time
A car is traveling at 70 miles per hour. Write a program that displays
the following:
The distance the car will travel in 6 hours
The distance the car will travel in 10 hours
The distance the car will travel in 15 hours
Solution
speed = (70)
distance1 = speed * 6
distance2 = speed * 10
distance3 = speed * 15
print("The distance the car will travel in 6 hours is: ", distance1)
print("The distance the car will travel in 10 hours is: ", distance2)
print("The distance the car will travel in 15 hours is: ", distance3)
Q 6 Sales Tax
Write a program that will ask the user to enter the amount of a
purchase. The program should
then compute the state and county sales tax. Assume the state sales
tax is 5 percent and the
county sales tax is 2.5 percent. The program should display the
amount of the purchase, the
state sales tax, the county sales tax, the total sales tax, and the total
of the sale (which is the sum
of the amount of purchase plus the total sales tax).
Solution
purchase = float(input("Enter the amount of purchase: "))
state_sales_tax =float(purchase * .05)
country_sales_tax = float(purchase * .025)
total_sales_tax = state_sales_tax + country_sales_tax
totalpurchase_cost = purchase + total_sales_tax
print(state_sales_tax)
print(country_sales_tax)
print(total_sales_tax)
print("The total cost of the purchase is: ",totalpurchase_cost)
Q7 Miles-per-Gallon
A car's miles-per-gallon (MPG) can be calculated with the following
formula:
MPG=Miles driven÷Gallons of gas used
Write a program that asks the user for the number of miles driven and
the gallons of gas used. It
should calculate the car's MPG and display the result.
Solution
miles_driven = float(input("Enter the miles driven: "))
gas_used = float(input("Enter the gas used: "))
MPG = miles_driven / gas_used
print("The miles per gallon is: ", MPG)
Q 8 Tip, Tax, and Total
Write a program that calculates the total amount of a meal purchased
at a restaurant. The
program should ask the user to enter the charge for the food, then
calculate the amounts of a 18
percent tip and 7 percent sales tax. Display each of these amounts
and the total
Solution
food_charge = float(input("Enter the food charge: "))
tip = food_charge * .18
sales_tax = food_charge * .07
total_cost = food_charge + tip + sales_tax
print("The tip is: ", tip)
print("The sales tax is: ", sales_tax)
print("The total cost is: ", total_cost)
Q 9 Celsius to Fahrenheit Temperature Converter
Write a program that converts Celsius temperatures to Fahrenheit
temperatures. The formula is
as follows:
F=95C+32
The program should ask the user to enter a temperature in Celsius,
then display the temperature
converted to Fahrenheit.
Solution
celcius = float(input('''Enter the temperature in celcius: '''))
fahrenheit = (celcius * 9/5) + 32
print("The temperature in fahrenheit is: ", fahrenheit)
Q 10 Ingredient Adjuster
A cookie recipe calls for the following ingredients:
1.5 cups of sugar
1 cup of butter
2.75 cups of flour
The recipe produces 48 cookies with this amount of the ingredients.
Write a program that asks
the user how many cookies he or she wants to make, then displays
the number of cups of each
ingredient needed for the specified number of cookies
Solution
cookies_wants = int(input("Enter the number of cookies he or she want: "))
sugar_cup = cookies_wants * 1.5 / 48
butter_cup = cookies_wants * 1 / 48
flour_cup = cookies_wants * 2.75 / 48
print("The number of cups of sugar needed is: ", sugar_cup)
print("The number of cups of butter needed is: ", butter_cup)
print("The number of cups of flour needed is: ", flour_cup)
chapter 3 Decision Structures and Boolean
Logic
Q1 Day of the Week
Write a program that asks the user for a number in the range of 1
through 7. The program
should display the corresponding day of the week, where 1 = Monday,
2 = Tuesday, 3 =
Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, and 7 = Sunday.
The program should
display an error message if the user enters a number that is outside
the range of 1 through 7.
Solution
Day = int(input("enter here number : "))
if Day == 1:
print("Monday")
elif Day == 2:
print("Tuesday")
elif Day == 3:
print("Wednesday")
elif Day == 4:
print("Thursday")
elif Day == 5:
print("Friday")
elif Day == 6:
print("Saturday")
elif Day == 7:
print("Sunday")
else:
print("error")
Q2 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
Solution
length1 = float(input("Enter the length of the rectangle 1: "))
width1 = float(input("Enter the width of the rectangle 1: "))
area1 = length1 * width1
length2 = float(input("Enter the length of the rectangle 2: "))
width2 = float(input("Enter the width of the rectangle 2: "))
area2 = length2 * width2
if area1 > area2:
print("The area of rectangle 1 is greater than rectangle 2")
elif area1 < area2:
print("The area of rectangle 2 is greater than rectangle 1")
else:
print("The area of rectangle 1 is equal to rectangle 2")
Q 3 Age Classifier
Write a program that asks the user to enter a person’s age. The
program should display a
message indicating whether the person is an infant, a child, a
teenager, or an adult. Following
are the guidelines:
If the person is 1 year old or less, he or she is an infant.
If the person is older than 1 year, but younger than 13 years, he or
she is a child.
If the person is at least 13 years old, but less than 20 years old, he or
she is a teenager.
If the person is at least 20 years old, he or she is an adult.
Solution
age = int(input("Enter the age of the person: "))
if age <= 1:
print("The person is an infant")
elif age < 13:
print("The person is a child")
elif age < 20:
print("The person is a teenager")
else:
print("The person is an adult")
Q4 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:
Solution
number = int(input("Enter the number: "))
if number == 1:
print("I")
elif number == 2:
print("II")
elif number == 3:
print("III")
elif number == 4:
print("IV")
elif number == 5:
print("V")
elif number == 6:
print("VI")
elif number == 7:
print("VII")
elif number == 8:
print("VIII")
elif number == 9:
print("IX")
elif number == 10:
print("X")
else:
print("error")
Q5 Write a program that asks the user to enter an object’s mass, then
calculates its weight. If the
object weighs more than 500 newtons, display a message indicating
that it is too heavy. If the
object weighs less than 100 newtons, display a message indicating
that it is too light.
Solution
mass = float (input ("Enter the mass of the object in kilogram: ",))
weight = mass * 9.8
if weight >= 500:
print("it is too heavy and weight is",weight,"newton")
elif weight <= 100:
print ("it is too light and weight is",weight,"newton")
else:
print ("its weight is",weight,"newton")
Q6 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
Solution
date = int (input("Enter the date in numeric format: "))
month = int (input("Enter the month in numeric format: "))
year = int(input("Enter the last two digit year: "))
magic_date = date * month
if magic_date == year:
print("The date is magic")
else:
print("The date is not magic")
Q7 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.
Solution
color1 = input('''Enter the first color name: ''')
color2 = input('''Enter the second color name: ''')
if color1 == "red" and color2 == "yellow":
print("orange")
elif color1 == "yellow" and color2 == "red":
print("orange")
elif color1 == "red" and color2 == "blue":
print("purple")
elif color1 == "blue" and color2 == "red":
print("purple")
elif color1 == "yellow" and color2 == "blue":
print("green")
elif color1 == "blue" and color2 == "yellow":
print("green")
else:
print(''' "error",please input the color name from group of colors: red,yellow,blue''')
Q8 Assume hot dogs come in packages of 10, and hot dog buns come
in packages of 8. Write a
program that calculates the number of packages of hot dogs and the
number of packages of hot
dog buns needed for a cookout, with the minimum amount of leftovers.
The program should ask
the user for the number of people attending the cookout and the
number of hot dogs each person
will be given. The program should display the following details:
The minimum number of packages of hot dogs required
The minimum number of packages of hot dog buns required
The number of hot dogs that will be left over
The number of hot dog buns that will be left over
Solution
Hot_Dogs_Per_Package = 10
Hot_Dogs_Buns_Per_Package = 8
attendes = int(input("Enter the number of attendes: "))
hot_dogs_per_person = int(input("Enter the number of hot dogs per person: "))
required_hot_dogs = attendes * hot_dogs_per_person
packages_of_hot_dogs = required_hot_dogs // Hot_Dogs_Per_Package
print("you require {packages_of_hot_dogs} hot dogs for the cookout: ")
print("you require {package_of_hot_dogs_buns} hot dog buns for the cookout: ")
remain_hotdogs = required_hot_dogs % Hot_Dogs_Per_Package
if remain_hotdogs != 0 :
print("you have {remain_hotdogs} left over hot dogs")
remain_hotdogs_buns = required_hot_dogs % Hot_Dogs_Buns_Per_Package
if remain_hotdogs_buns != 0:
print("you have {remain_hotdogs_buns} left over hot dog buns")
Q9 Roulette Wheel Colors
On a roulette wheel, the pockets are numbered from 0 to 36. The
colors of the pockets are as
follows:
Pocket 0 is green.
For pockets 1 through 10, the odd-numbered pockets are red and the
even-numbered
pockets are black.
For pockets 11 through 18, the odd-numbered pockets are black and
the even-numbered
pockets are red.
For pockets 19 through 28, the odd-numbered pockets are red and the
even-numbered
pockets are black.
For pockets 29 through 36, the odd-numbered pockets are black and
the even-numbered
pockets are red.
Write a program that asks the user to enter a pocket number and
displays whether the pocket is
green, red, or black. The program should display an error message if
the user enters a number
that is outside the range of 0 through 36.
10. Money Counting Game
Create a change-counting game that gets the
Solution
pocket_number = int(input('''Enter the pocket number: '''))
if pocket_number == 0 :
print("green")
elif pocket_number <= 10 and pocket_number % 2 == 0 :
print("black")
elif pocket_number <=10 and pocket_number % 2 != 0 :
print("red")
elif pocket_number <=18 and pocket_number % 2 == 0 :
print("red")
elif pocket_number <=18 and pocket_number % 2 != 0 :
print("black")
elif pocket_number <= 28 and pocket_number % 2 == 0 :
print("black")
elif pocket_number <=28 and pocket_number % 2 != 0 :
print("red")
elif pocket_number <= 36 and pocket_number % 2 != 0 :
print("black")
elif pocket_number <= 36 and pocket_number % 2 == 0 :
print ("red")
else:
print("error")
Q 10 Money Counting 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
Solution
pennies = .100
nickels = .25
dimes = .10
quarters = .4
Pennies= float(input("Enter the number of pennies: "))
Nickels = float(input("Enter the number of nickels: "))
Dimes = float (input("Enter the number of dimes: "))
Quarters = float(input("Enter the number of quarters: "))
Pennies *= pennies
Nickels *= nickels
Dimes *= dimes
Quarters *= quarters
total = Pennies + Nickels + Dimes + Quarters
if total == 1:
print("Congratulations! You won the game!")
elif total > 1:
print("The amount enter is greater than 1 dollar")
else:
print ("The amount enter is less than 1 dollar")
Chapter 4 Repetition Structures
Topics
Q1 The Bug Collector Problem
A bug collector collects bugs every day for five days. Write a program
that keeps a running total
of the number of bugs collected during the five days. The loop should
ask for the number of
bugs collected for each day, and when the loop is finished, the
program should display the total
number of bugs collected.
Solution
total_bugs = 0
for day in range(1, 6):
bugs_collected = int(input(f"Enter the number of bugs collected on day {day}: "))
total_bugs += bugs_collected
print(f"\nTotal number of bugs collected in five days: {total_bugs}")
Q2 Calories Burned
Running on a particular treadmill you burn 4.2 calories per minute.
Write a program that uses a
loop to display the number of calories burned after 10, 15, 20, 25, and
30 minutes.
Solution
time_durations = [10, 15, 20, 25, 30]
for time in time_durations:
calories_burned = calories_per_minute * time
print(f'After {time} minutes, you have burned {calories_burned} calories.')
Q 3 Budget Analysis
Write a program that asks the user to enter the amount that he or she
has budgeted for a month.
A loop should then prompt the user to enter each of his or her
expenses for the month and keep
a running total. When the loop finishes, the program should display
the amount that the user is
over or under budget.
Solution
budget = float(input("Enter your budget for the month: $"))
total_expenses = 0
while True:
expense = input("Enter an expense amount (or 'done' to finish): $")
if expense.lower() == 'done':
break
try:
expense = float(expense)
total_expenses += expense
except ValueError:
print("Invalid input. Please enter a valid expense amount.")
difference = budget - total_expenses
print("\nBudget: ${:.2f}".format(budget))
print("Total Expenses: ${:.2f}".format(total_expenses))
if difference >= 0:
print("You are under budget by ${:.2f}".format(difference))
else:
print("You are over budget by ${:.2f}".format(abs(difference)))
Q4 if a train travels 40 miles per hour for three hours, the distance
traveled is 120
miles. Write a program that asks the user for the speed of a vehicle (in
miles per hour) and the
number of hours it has traveled. It should then use a loop to display
the distance the vehicle has
traveled for each hour of that time period.
Solution
speed = float(input("Enter the speed of the vehicle (in miles per hour): "))
hours = int(input("Enter the number of hours the vehicle has traveled: "))
print("\nHour\tDistance Traveled")
print("-----------------------")
for hour in range(1, hours + 1):
distance = speed * hour
print(f"{hour}\t{distance} miles")
Q5 Write a program that uses nested loops to collect data and calculate
the average rainfall over a
period of years. The program should first ask for the number of years.
The outer loop will
iterate once for each year. The inner loop will iterate twelve times,
once for each month. Each
iteration of the inner loop will ask the user for the inches of rainfall for
that month. After all
iterations, the program should display the number of months, the total
inches of rainfall, and the
average rainfall per month for the entire period.
Solution
total_rainfall = 0
total_months = num_years * 12
for year in range(1, num_years + 1):
for month in range(1, 13):
rainfall = float(input(f"Enter the inches of rainfall for Year {year}, Month {month}: "))
total_rainfall += rainfall
average_rainfall = total_rainfall / total_months
print("\nNumber of Months:", total_months)
Q6 Writea program that displays a table of the Celsius temperatures 0
through 20 and their
Fahrenheit equivalents. The formula for converting a temperature from
Celsius to Fahrenheit is
F=95C+32
where F is the Fahrenheit temperature, and C is the Celsius
temperature. Your program must
use a loop to display the table.
Solution
print("Celsius\tFahrenheit")
print("------------------")
for celsius in range(21):
fahrenheit = 9/5 * celsius + 32
print(f"{celsius}\t{fahrenheit}")
Q7 Write a program that calculates the amount of money a person
would earn over a period of time
if his or her salary is one penny the first day, two pennies the second
day, and continues to
double each day. The program should ask the user for the number of
days. Display a table
showing what the salary was for each day, then show the total pay at
the end of the period. The
output should be displayed in a dollar amount, not the number of
pennies.
Solution
um_days = int(input("Enter the number of days: "))
total_pay = 0
daily_salary = 0.01
print("Day\tSalary")
print("--------------")
for day in range(1, num_days + 1):
print(f"{day}\t${daily_salary:.2f}")
total_pay += daily_salary
daily_salary *= 2
print("\nTotal Pay over", num_days, "days: ${:.2f}".format(total_pay))
Q8 Write a program with a loop that asks the user to enter a series of
positive numbers. The user
should enter a negative number to signal the end of the series. After
all the positive numbers
have been entered, the program should display their sum.
Solution
sum_positive_numbers = 0
while True:
number = float(input("Enter a positive number (or a negative number to end): "))
if number >= 0:
sum_positive_numbers += number
else:
break
print("\nSum of positive numbers entered:", sum_positive_numbers)
Q9 Assuming the ocean’s level is currently rising at about 1.6
millimeters per year, create an
application that displays the number of millimeters that the ocean will
have risen each year for
the next 25 years.
Solution
rise_rate = 1.6
print("Year\tSea Level Rise (mm)")
print("------------------------")
for year in range(1, 26):
sea_level_rise = rise_rate * year
print(f"{year}\t{sea_level_rise:.2f}")
Q 10 At one college, the tuition for a full-time student is $8,000 per
semester. It has been announced
that the tuition will increase by 3 percent each year for the next 5
years. Write a program with a
loop that displays the projected semester tuition amount for the next 5
years.
Solution
tuition = 8000
increase_rate = 0.03
print("Year\tProjected Tuition")
print("----------------------")
for year in range(1, 6):
tuition = tuition + (tuition * increase_rate)
print(f"{year}\t${tuition:.2f}")
chapter 5 Functions
Q 1 Write a program that asks the user to enter a distance in
kilometers, then converts that distance
to miles.
Solution
Kilometers = float (input("Enter the distance in kilometers: "))
Miles=Kilometers * 0.6214
print(f"{Kilometers} kilometers is equal to {Miles:.2f} miles")
Q 2 write a program that calculates and displays the county and state
sales tax on a
purchase. If you have already written that program, redesign it so the
subtasks are in functions.
Solution
def calculate_state_sales_tax(purchase):
state_sales_tax = purchase * 0.05
return state_sales_tax
def calculate_county_sales_tax(purchase):
county_sales_tax = purchase * 0.025
return county_sales_tax
def calculate_total_sales_tax(state_sales_tax, county_sales_tax):
total_sales_tax = state_sales_tax + county_sales_tax
return total_sales_tax
def calculate_total_purchase_cost(purchase, total_sales_tax):
total_purchase_cost = purchase + total_sales_tax
return total_purchase_cost
purchase = float(input("Enter the amount of purchase: "))
state_sales_tax = calculate_state_sales_tax(purchase)
county_sales_tax = calculate_county_sales_tax(purchase)
total_sales_tax = calculate_total_sales_tax(state_sales_tax, county_sales_tax)
total_purchase_cost = calculate_total_purchase_cost(purchase, total_sales_tax)
print("The state sales tax is: ", state_sales_tax)
print("The county sales tax is: ", county_sales_tax)
print("The total sales tax is: ", total_sales_tax)
print("The total cost of the purchase is: ", total_purchase_cost)
Q 3 Many financial experts advise that property owners should insure
their homes or buildings for at
least 80 percent of the amount it would cost to replace the structure.
Write a program that asks
the user to enter the replacement cost of a building, then displays the
minimum amount of
insurance he or she should buy for the property.
Solution
def calculate_insurance(replacement_cost):
minimum_insurance = replacement_cost * 0.8
return minimum_insurance
replacement_cost = float(input("Enter the replacement cost of the building: "))
minimum_insurance = calculate_insurance(replacement_cost)
print(f"The minimum amount of insurance to buy is: {minimum_insurance}")
Q 4 Writea program that asks the user to enter the monthly costs for
the following expenses
incurred from operating his or her automobile: loan payment,
insurance, gas, oil, tires, and
maintenance. The program should then display the total monthly cost
of these expenses, and the
total annual cost of these expenses.
Solution
def calculate_total_monthly_cost(loan_payment, insurance, gas, oil, tires, maintenance):
total_monthly_cost = loan_payment + insurance + gas + oil + tires + maintenance
return total_monthly_cost
def calculate_total_annual_cost(total_monthly_cost):
total_annual_cost = total_monthly_cost * 12
return total_annual_cost
loan_payment = float(input("Enter the monthly cost for loan payment: "))
insurance = float(input("Enter the monthly cost for insurance: "))
gas = float(input("Enter the monthly cost for gas: "))
oil = float(input("Enter the monthly cost for oil: "))
tires = float(input("Enter the monthly cost for tires: "))
maintenance = float(input("Enter the monthly cost for maintenance: "))
total_monthly_cost = calculate_total_monthly_cost(loan_payment, insurance, gas, oil, tires,
maintenance)
total_annual_cost = calculate_total_annual_cost(total_monthly_cost)
print(f"The total monthly cost of these expenses is: {total_monthly_cost}")
print(f"The total annual cost of these expenses is: {total_annual_cost}")
Q5A county collects property taxes on the assessment value of
property, which is 60 percent of the
property’s actual value. For example, if an acre of land is valued at
$10,000, its assessment
value is $6,000. The property tax is then 72¢ for each $100 of the
assessment value. The tax for
the acre assessed at $6,000 will be $43.20. Write a program that asks
for the actual value of a
piece of property and displays the assessment value and property tax.
Solution
def calculate_assessment_value(actual_value):
assessment_value = actual_value * 0.6
return assessment_value
def calculate_property_tax(assessment_value):
property_tax = (assessment_value / 100) * 0.72
return property_tax
actual_value = float(input("Enter the actual value of the property: "))
assessment_value = calculate_assessment_value(actual_value)
property_tax = calculate_property_tax(assessment_value)
print(f"The assessment value of the property is: {assessment_value}")
print(f"The property tax is: {property_tax}")
Q6A nutritionist who works for a fitness club helps members by
evaluating their diets. As part of
her evaluation, she asks members for the number of fat grams and
carbohydrate grams that they
consumed in a day. Then, she calculates the number of calories that
result from the fat, using the
following formula
Solution
def calculate_calories_from_fat(fat_grams):
calories_from_fat = fat_grams * 9
return calories_from_fat
def calculate_calories_from_carbs(carb_grams):
calories_from_carbs = carb_grams * 4
return calories_from_carbs
fat_grams = float(input("Enter the number of fat grams consumed: "))
carb_grams = float(input("Enter the number of carbohydrate grams consumed: "))
calories_from_fat = calculate_calories_from_fat(fat_grams)
calories_from_carbs = calculate_calories_from_carbs(carb_grams)
print(f"The number of calories from fat is: {calories_from_fat}")
print(f"The number of calories from carbs is: {calories_from_carbs}")
Q 7There are three seating categories at a stadium. Class A seats cost
$20, Class B seats cost $15,
and Class C seats cost $10. Write a program that asks how many
tickets for each class of seats
were sold, then displays the amount of income generated from ticket
sales.
Solution
def calculate_income(class_a_tickets, class_b_tickets, class_c_tickets):
class_a_income = class_a_tickets * 20
class_b_income = class_b_tickets * 15
class_c_income = class_c_tickets * 10
total_income = class_a_income + class_b_income + class_c_income
return total_income
class_a_tickets = int(input("Enter the number of Class A tickets sold: "))
class_b_tickets = int(input("Enter the number of Class B tickets sold: "))
class_c_tickets = int(input("Enter the number of Class C tickets sold: "))
total_income = calculate_income(class_a_tickets, class_b_tickets, class_c_tickets)
print(f"The amount of income generated from ticket sales is: {total_income}")
Q8A painting company has determined that for every 112 square feet
of wall space, one gallon of
paint and eight hours of labor will be required. The company charges
$35.00 per hour for labor.
Write a program that asks the user to enter the square feet of wall
space to be painted and the
price of the paint per gallon. The program should display the following
data:
The number of gallons of paint required
The hours of labor required
The cost of the paint
The labor charges
The total cost of the paint job
Solution
def calculate_paint_and_labor(square_feet, paint_price_per_gallon, labor_rate):
gallons_of_paint = square_feet / 112
hours_of_labor = gallons_of_paint * 8
cost_of_paint = gallons_of_paint * paint_price_per_gallon
labor_charges = hours_of_labor * labor_rate
total_cost = cost_of_paint + labor_charges
return (gallons_of_paint, hours_of_labor, cost_of_paint, labor_charges, total_cost)
square_feet = float(input("Enter the square feet of wall space to be painted: "))
paint_price_per_gallon = float(input("Enter the price of the paint per gallon: "))
labor_rate = 35.00
results = calculate_paint_and_labor(square_feet, paint_price_per_gallon, labor_rate)
print(f"The number of gallons of paint required: {results[0]}")
print(f"The hours of labor required: {results[1]}")
print(f"The cost of the paint: ${results[2]:.2f}")
print(f"The labor charges: ${results[3]:.2f}")
print(f"The total cost of the paint job: ${results[4]:.2f}")
Q9A retail company must file a monthly sales tax report listing the total
sales for the month, and
the amount of state and county sales tax collected. The state sales tax
rate is 5 percent and the
county sales tax rate is 2.5 percent. Write a program that asks the
user to enter the total sales for
the month. From this figure, the application should calculate and
display the following:
The amount of county sales tax
The amount of state sales tax
The total sales tax (county plus state)
Solution
def calculate_sales_tax():
total_sales = float(input("Enter the total sales for the month: "))
state_sales_tax_rate = 0.05
county_sales_tax_rate = 0.025
county_sales_tax = total_sales * county_sales_tax_rate
state_sales_tax = total_sales * state_sales_tax_rate
total_sales_tax = county_sales_tax + state_sales_tax
print(f"The amount of county sales tax is: ${county_sales_tax:.2f}")
print(f"The amount of state sales tax is: ${state_sales_tax:.2f}")
print(f"The total sales tax is: ${total_sales_tax:.2f}")
calculate_sales_tax()
Q 10 One foot equals 12 inches. Write a function named feet_to_inches
that accepts a number of
feet as an argument and returns the number of inches in that many
feet. Use the function in a
program that prompts the user to enter a number of feet then displays
the number of inches in
that many feet
Solution
def feet_to_inches(feet):
inches = feet * 12
return inches
feet = float(input("Enter the distance in feet: "))
print(f"{feet} feet is equal to {feet_to_inches(feet)} inches")
CHAPTER 6 Files and Exceptions
Q 1 Assume a file containing a series of integers is named numbers.txt
and exists on the
computer’s disk. Write a program that displays all of the numbers in
the file.
Solution
file_name = "numbers.txt"
try:
with open(file_name, 'r') as file:
lines = file.readlines()
for line in lines:
number = int(line)
print(number)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except ValueError:
print(f"Error: Could not convert a line in '{file_name}' to an integer.")
except Exception as e:
print(f"An error occurred: {e}")
Q 2 Write a program that asks the user for the name of a file. The
program should display only the
first five lines of the file’s contents. If the file contains less than five
lines, it should display the
file’s entire contents.
Solution
file_name = input("Enter the name of the file: ")
try:
with open(file_name, 'r') as file:
lines = file.readlines()
for line in lines[:5]:
print(line, end='')
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 3 Write a program that asks the user for the name of a file. The
program should display the
contents of the file with each line preceded with a line number
followed by a colon. The line
numbering should start at 1
Solution
file_name = input("Enter the name of the file: ")
try:
with open(file_name, 'r') as file:
lines = file.readlines()
for i, line in enumerate(lines, start=1):
print(f"{i}: {line}", end='')
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 4 Assume a file containing a series of names (as strings) is named
names.txt and exists on the
computer’s disk. Write a program that displays the number of names
that are stored in the file.
Solution
file_name = "names.txt"
count = 0
try:
with open(file_name, 'r') as file:
for line in file:
count += 1
print(f"The number of names in the file is: {count}")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 5 Assume a file containing a series of integers is named numbers.txt
and exists on the
computer’s disk. Write a program that reads all of the numbers stored
in the file and calculates
their total.
Solution
file_name = "numbers.txt"
total = 0
try:
with open(file_name, 'r') as file:
for line in file:
number = int(line)
total += number
print(f"The total sum of numbers in the file is: {total}")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except ValueError:
print(f"Error: Could not convert a line in '{file_name}' to an integer.")
except Exception as e:
print(f"An error occurred: {e}")
Q 6 Assume a file containing a series of integers is named numbers.txt
and exists on the
computer’s disk. Write a program that calculates the average of all the
numbers stored in the
file.
Solution
file_name = "numbers.txt"
total = 0
count = 0
try:
with open(file_name, 'r') as file:
for line in file:
number = int(line)
total += number
count += 1
if count == 0:
print("The file is empty.")
else:
average = total / count
print(f"The average of the numbers in the file is: {average}")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except ValueError:
print(f"Error: Could not convert a line in '{file_name}' to an integer.")
except Exception as e:
print(f"An error occurred: {e}")
Q 7 Write a program that writes a series of random numbers to a file.
Each random number should
be in the range of 1 through 500. The application should let the user
specify how many random
numbers the file will hold.
Solution
import random
num_numbers = int(input("Enter the number of random numbers: "))
file_name = "random_numbers.txt"
with open(file_name, 'w') as file:
for _ in range(num_numbers):
random_number = random.randint(1, 500)
file.write(str(random_number) + '\n')
print(f"{num_numbers} random numbers have been written to '{file_name}'.")
Q 8 This exercise assumes you have completed Programming
Exercise 7, Random Number File
Writer. Write another program that reads the random numbers from
the file, displays the
numbers, then displays the following data:
The total of the numbers
The number of random numbers read from the file
Solution
file_name = "random_numbers.txt"
total = 0
count = 0
try:
with open(file_name, 'r') as file:
numbers = [int(line) for line in file]
for number in numbers:
total += number
count += 1
print(f"The numbers from the file: {numbers}")
print(f"The total of the numbers: {total}")
print(f"The number of random numbers read from the file: {count}")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except ValueError:
print(f"Error: Could not convert a line in '{file_name}' to an integer.")
except Exception as e:
print(f"An error occurred: {e}")
Q 9 Modify the program that you wrote for Exercise 6 so it handles the
following exceptions:
It should handle any IOError exceptions that are raised when the file is
opened and data is
read from it.
It should handle any ValueError exceptions that are raised when the
items that are read
from the file are converted to a number.
Solution
file_name = "numbers.txt"
try:
with open(file_name, 'r') as file:
lines = file.readlines()
for line in lines:
try:
number = int(line)
print(number)
except ValueError:
print(f"Error: Could not convert '{line.strip()}' to an integer.")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except IOError as e:
print(f"An error occurred: {e}")
except Exception as e:
print(f"An error occurred: {e}")
Q 10 The Springfork Amateur Golf Club has a tournament every
weekend. The club president has
asked you to write two programs:
1. A program that will read each player’s name and golf score as
keyboard input, then save
these as records in a file named golf.txt. (Each record will have a field
for the player’s
name and a field for the player’s score.)
2. A program that reads the records from the golf.txt file and displays
them
Solution
filename = "golf.txt"
num_players = int(input("Enter the number of players: "))
with open(filename, 'w') as file:
for _ in range(num_players):
name = input("Enter player's name: ")
score = input("Enter player's score: ")
file.write(f"{name}, {score}\n")
filename = "golf.txt"
try:
with open(filename, 'r') as file:
for line in file:
name, score = line.strip().split(',')
print(f"Player: {name}, Score: {score}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
CHAPTER 7 Lists and Tuples
Q 1 Design a program that asks the user to enter a store’s sales for
each day of the week. The
amounts should be stored in a list. Use a loop to calculate the total
sales for the week and
display the result.
Solution
sales = []
for day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]:
sales.append(float(input(f"Enter sales for {day}: "))
total_sales = sum(sales)
print(f"The total sales for the week is: {total_sales}")
Q 2 Design a program that generates a seven-digit lottery number.
The program should generate
seven random numbers, each in the range of 0 through 9, and assign
each number to a list
element.
Solution
import random
lottery_numbers = []
for _ in range(7):
lottery_numbers.append(random.randint(0, 9))
for number in lottery_numbers:
print(number)
Q 3 Design a program that lets the user enter the total rainfall for each
of 12 months into a list. The
program should calculate and display the total rainfall for the year, the
average monthly rainfall,
the months with the highest and lowest amounts.
Solution
rainfall = []
for month in range(1, 13):
rainfall.append(float(input(f"Enter total rainfall for month {month}: "))
total_rainfall = sum(rainfall)
average_rainfall = total_rainfall / 12
max_rainfall_month = rainfall.index(max(rainfall)) + 1
min_rainfall_month = rainfall.index(min(rainfall)) + 1
print(f"Total rainfall for the year: {total_rainfall} inches")
print(f"Average monthly rainfall: {average_rainfall} inches")
print(f"Month with the highest rainfall: Month {max_rainfall_month}")
print(f"Month with the lowest rainfall: Month {min_rainfall_month}")
Q 4 Design a program that asks the user to enter a series of 20
numbers. The program should store
the numbers in a list then display the following data:
The lowest number in the list
The highest number in the list
The total of the numbers in the list
The average of the numbers in the list
Solution
numbers = []
for i in range(20):
num = int(input("Enter a number: "))
numbers.append(num)
min_num = min(numbers)
max_num = max(numbers)
total = sum(numbers)
average = total / len(numbers)
print(f"The lowest number is {min_num}")
print(f"The highest number is {max_num}")
print(f"The total of the numbers is {total}")
print(f"The average of the numbers is {average}")
Q 5 Write a program that reads the contents of the file into a list. The
program should then ask the
user to enter a charge account number. The program should
determine whether the number is
valid by searching for it in the list. If the number is in the list, the
program should display a
message indicating the number is valid. If the number is not in the list,
the program should
display a message indicating the number is invalid.
Solution
file_name = "charge_accounts.txt"
try:
with open(file_name, 'r') as file:
charge_accounts = file.read().splitlines()
user_input = input("Enter a charge account number: ")
if user_input in charge_accounts:
print("The number is valid.")
else:
print("The number is invalid.")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 6 In a program, write a function that accepts two arguments: a list,
and a number n. Assume that
the list contains numbers. The function should display all of the
numbers in the list that are
greater than the number n.
Solution
def display_numbers_greater_than_n(numbers, n):
greater_numbers = [num for num in numbers if num > n]
for num in greater_numbers:
print(num)
Q 7 The program should read the
student’s answers for each of the 20 questions from a text file and
store the answers in another
list. (Create your own text file to test the application.) After the
student’s answers have been
read from the file, the program should display a message indicating
whether the student passed
or failed the exam. (A student must correctly answer 15 of the 20
questions to pass the exam.) It
should then display the total number of correctly answered questions,
the total number of
incorrectly answered questions, and a list showing the question
numbers of the incorrectly
answered questions.
Solution
file_name = "student_answers.txt"
correct_answers = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']
try:
with open(file_name, 'r') as file:
student_answers = file.read().splitlines()
num_correct = sum([1 for i in range(20) if student_answers[i] == correct_answers[i]])
num_incorrect = 20 - num_correct
incorrect_indices = [i+1 for i in range(20) if student_answers[i] != correct_answers[i]]
if num_correct >= 15:
print("The student passed the exam.")
else:
print("The student failed the exam.")
print(f"Total number of correctly answered questions: {num_correct}")
print(f"Total number of incorrectly answered questions: {num_incorrect}")
print("The question numbers of the incorrectly answered questions:")
for i in incorrect_indices:
print(i)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 8 Write a program that reads the contents of the two files into two
separate lists. The user should
be able to enter a boy’s name, a girl’s name, or both, and the
application will display messages
indicating whether the names were among the most popular.
Solution
def search_names():
with open("GirlNames.txt", "r") as girl_file:
girl_names = girl_file.read().splitlines()
with open("BoyNames.txt", "r") as boy_file:
boy_names = boy_file.read().splitlines()
user_input = input("Enter a name: ")
if user_input in girl_names:
print(f"{user_input} is among the most popular girl names.")
if user_input in boy_names:
print(f"{user_input} is among the most popular boy names.")
Q 9 The file contains the midyear population of the United States, in
thousands,
during the years 1950 through 1990. The first line in the file contains
the population for 1950,
the second line contains the population for 1951, and so forth.
Write a program that reads the file’s contents into a list. The program
should display the
following data:
The average annual change in population during the time period
The year with the greatest increase in population during the time
period
The year with the smallest increase in population during the time
period
Solution
with open("USPopulation.txt", "r") as file:
populations = [int(line) for line in file.readlines()]
annual_changes = [populations[i+1] - populations[i] for i in range(len(populations)-1)]
average_change = sum(annual_changes) / len(annual_changes)
max_increase_year = annual_changes.index(max(annual_changes)) + 1951
min_increase_year = annual_changes.index(min(annual_changes)) + 1951
print(f"The average annual change in population during the time period is {average_change}.")
print(f"The year with the greatest increase in population during the time period is
{max_increase_year}.")
print(f"The year with the smallest increase in population during the time period is
{min_increase_year}.")
Q 10 Write a program that lets the user enter the name of a team,
then displays the number of times
that team has won the World Series in the time period from 1903
through 2009.
Solution
with open("WorldSeriesWinners.txt", "r") as file:
winners_list = file.read().splitlines()
user_input = input("Enter the name of a team: ")
team_wins = winners_list.count(user_input)
print(f"{user_input} won the World Series {team_wins} times from 1903 through 2009.")
CHAPTER 8 : More About Strings
Q 1 Write a program that gets a string containing a person’s first,
middle, and last names, and
displays their first, middle, and last initials. For example, if the user
enters John William Smith,
the program should display J. W. S.
Solution
full_name = input("Enter your full name: ")
names = full_name.split()
initials = [name[0] + "." for name in names]
print(" ".join(initials))
Q 2 Write a program that asks the user to enter a series of single-digit
numbers with nothing
separating them. The program should display the sum of all the single
digit numbers in the
string. For example, if the user enters 2514, the method should return
12, which is the sum of 2,
5, 1, and 4.
Solution
numbers_str = input("Enter a series of single-digit numbers: ")
total = sum(int(digit) for digit in numbers_str if digit.isdigit())
print(total)
Q 3 Write a program that reads a string from the user containing a
date in the form mm/dd/yyyy. It
should print the date in the format March 12, 2018.
Solution
from datetime import datetime
date_str = input("Enter a date in the form mm/dd/yyyy: ")
date = datetime.strptime(date_str, "%m/%d/%Y")
formatted_date = date.strftime("%B %d, %Y")
print(formatted_date)
Q 4 Write a program that asks the user to enter a string, then converts
that string to Morse code.
Solution
MORSE_CODE_DICT = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.',
'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.',
'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..',
'0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..', '9': '----.',
'.': '.-.-.-', ',': '--..--', '?': '..--..', "'": '.----.', '!': '-.-.--', '/': '-..-.'
def text_to_morse_code(text):
morse_code = ''
for char in text:
if char.upper() in MORSE_CODE_DICT:
morse_code += MORSE_CODE_DICT[char.upper()] + ' '
else:
morse_code += ' '
return morse_code.strip()
user_input = input("Enter a string: ")
print(text_to_morse_code(user_input))
Q 5 Write a program that asks the user to enter a 10-character
telephone number in the format XXXXXX-
XXXX. The application should display the telephone number with any
alphabetic
characters that appeared in the original translated to their numeric
equivalent. For example, if
the user enters 555-GET-FOOD, the application should display 555-
438-3663.
Solution
telephone_number = input("Enter a 10-character telephone number in the format XXXXXX-XXXX: ")
translated_number = ''
for char in telephone_number:
if char.isalpha():
if char in 'ABC': translated_number += '2'
elif char in 'DEF': translated_number += '3'
elif char in 'GHI': translated_number += '4'
elif char in 'JKL': translated_number += '5'
elif char in 'MNO': translated_number += '6'
elif char in 'PQRS': translated_number += '7'
elif char in 'TUV': translated_number += '8'
elif char in 'WXYZ': translated_number += '9'
else:
translated_number += char
print(translated_number)
Q 6 Write a program that reads the file’s contents and calculates the
average number of
words per sentence
Solution
try:
with open("text.txt", 'r') as file:
sentences = file.readlines()
total_words = sum(len(sentence.split()) for sentence in sentences)
average_words_per_sentence = total_words / len(sentences)
print(f"The average number of words per sentence is {average_words_per_sentence:.2f}")
except FileNotFoundError:
print(f"Error: The file 'text.txt' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 7 Character Analysis
Solution
try:
with open("text.txt", 'r') as file:
text = file.read()
character_count = len(text)
word_count = len(text.split())
line_count = text.count('\n') + 1 # Add one for the last line
print(f"Character count: {character_count}")
print(f"Word count: {word_count}")
print(f"Line count: {line_count}")
except FileNotFoundError:
print(f"Error: The file 'text.txt' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 8 If you have downloaded the source code you will find a file named
text.txt folder.
Write a program that reads the file’s contents and
determines the following:
The number of uppercase letters in the file
The number of lowercase letters in the file
The number of digits in the file
The number of whitespace characters in the file
Solution
try:
with open("text.txt", "r") as file:
content = file.read()
upper_count = sum(1 for char in content if char.isupper())
lower_count = sum(1 for char in content if char.islower())
digit_count = sum(1 for char in content if char.isdigit())
whitespace_count = sum(1 for char in content if char.isspace())
print(f"Number of uppercase letters: {upper_count}")
print(f"Number of lowercase letters: {lower_count}")
print(f"Number of digits: {digit_count}")
print(f"Number of whitespace characters: {whitespace_count}")
except FileNotFoundError:
print("Error: The file 'text.txt' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q 9 Write a program with a function that accepts a string as an
argument and returns a copy of the
string with the first character of each sentence capitalized. For
instance, if the argument is
“hello. my name is Joe. what is your name?” the function should return
the string “Hello. My
name is Joe. What is your name?” The program should let the user
enter a string and then pass it
to the function. The modified string should be displayed.
Solution
def capitalize_first_char(sentences):
return '. '.join(map(str.capitalize, sentences.split('. '))
user_input = input("Enter a string: ")
modified_string = capitalize_first_char(user_input)
print(modified_string)
Q 10 Write a program with a function that accepts a string as an
argument and returns the number of
vowels that the string contains. The application should have another
function that accepts a
string as an argument and returns the number of consonants that the
string contains. The
application should let the user enter a string, and should display the
number of vowels and the
number of consonants it contains
Solution
def count_vowels(string):
return sum(1 for char in string if char.lower() in 'aeiou')
def count_consonants(string):
return sum(1 for char in string if char.isalpha() and char.lower() not in 'aeiou')
user_input = input("Enter a string: ")
vowel_count = count_vowels(user_input)
consonant_count = count_consonants(user_input)
print(f"The number of vowels in the string is: {vowel_count}")
print(f"The number of consonants in the string is: {consonant_count}")