Question

In: Computer Science

For this portion of the lab, you will reuse the program you wrote before. That means...

For this portion of the lab, you will reuse the program you wrote before.

That means you will open the lab you wrote in the previous assignment and change it. You should NOT start from scratch. Also, all the requirements/prohibitions from the previous lab MUST also be included /omitted from this lab.

Redesign the solution in the following manner:
1. Create a menu and ask the user which of the following conversions they wish to perform:
a. Miles to kilometers

b. Gallons to liters

c. Pounds to kilograms

d. Inches to centimeters

e. Fahrenheit to Celsius

2. Your program must raise an exception if the user chooses any item not on the menu presented. Along with raising an exception, write the code to handle this exception.
3. Once the user has chosen a menu item the program should:

a. Ask the user for a value to convert. Refer to the input validations in Lab 4. Your program must raise and exception, and handle the exception, if an input errors occurs.

b. Perform the conversion and write the original value, the original unit, the converted value, and the converted unit to an output file named conversions.txt.

c. Repeat steps a and b 10 times (in a loop).

I have written this code before. I already have added step number 1: the menu. Please add in the code the other requirements: step 2, and step 3 a. b. and c. Thank you!

#Conversions.py

def MilesToKm(Miles):
Km = Miles * 1.6
print(f"Miles: {format(Miles,'.2f')}, kilometers: {format(Km,'.2f')}")
def FahToCel(Fahrenheit):
Celsius = (Fahrenheit - 32) * 5 / 9
print(f"farehnheit: {format(Fahrenheit,'.2f')}, celsius: {format(Celsius,'.2f')}")
def GalToLit(Gallons):
Liters = Gallons * 3.9
print(f"gallons: {format(Gallons,'.2f')}, liters: {format(Liters,'.2f')}")
def PoundsToKg(Pounds):
Kg = Pounds * 3.45
print(f"pounds: {format(Pounds,'.2f')}, kilograms: {format(Kg,'.2f')}")
def InchesToCm(Inches):
Cm = Inches * 2.54
print(f"inches: {format(Inches,'.2f')}, centimeters: {format(Cm,'.2f')}")

#Main.py

#Import the package
from Conversions import *
#Create main function to give choice of conversion
def main():
#Intialize the string
string = '''
1: Convert miles to km
2: Convert fahrenheit to celsius
3: Convert gallons to liters
4: Convert pounds to kg
5: Convert inches to cm'''
#Initialize the tupels
metric_name = ('miles','fahrenheit','gallons','pounds','inches')
convert_name = ('km','celsius','liters','kg','cm')
#Print the string
print(string)
#Get the input
choice = int(input('Which of the given conversions would you like to perform? Enter your choice from 1 to 5: '))
#Set count as "3"
count = 3
#Initialize the boolean variable
flag = True
#Execte the "while" loop
while(flag):
#Get the input
input_value = float(input("Enter how much {0} would you like to convert into {1}: "
.format(metric_name[choice-1] , convert_name[choice-1])))
#Check for the negative inputs
if input_value < 0:
#Decrement count by "1"
count -= 1
#Print the invalid message
print('Invalid input! You have',count,'chance(s) to enter a valid input')
#Otherwise
else:
#Check for the choice "1"
if choice == 1:
#Call the function
MilesToKm(input_value)
#Check for the choice "2"
if choice ==2:
#Check whether the input is greater than or equal to "1000"
if input_value >= 1000:
#Decrment the count "1"
count -= 1
#Print the message
print('Invalid input! You have',
count,'chance(s) to enter a valid input')
#Otherwise
else:
#Call the function
FahToCel(input_value)
#Check for the choice "3"
if choice == 3:
#Call the function
GalToLit(input_value)
#Check for the choice "4"
if choice == 4:
#Call the function
PoundsToKg(input_value)
#Check for the choice "5"
if choice == 5:
#Call the function
InchesToCm(input_value)
#Checck whether the count is "0"
if count == 0:
#Set boolean value as "False"
flag = False
#Call the function
main()

Solutions

Expert Solution

The code has been modified to meet all the requirements.

#The Code is written in Allman Style Please REMOVE brackets before running CODE. Thumbs up if the code helps

conversion.py

def milestokm(miles):
{
km = miles * 1.6
print(f"Miles: {format(miles,'.2f')}, kilometers: {format(km,'.2f')}")
return km
}
def fahtocel(fahrenheit):
{
celsius = (fahrenheit - 32) * 5 / 9
print(f"fahrenheit: {format(fahrenheit,'.2f')}, celsius: {format(celsius,'.2f')}")
return celsius
}
def galtolit(gallons):
{
liters = gallons * 3.9
print(f"gallons: {format(gallons,'.2f')}, liters: {format(liters,'.2f')}")
return litres
}
def poundstokg(pounds):
{
kg = pounds * 3.45
print(f"pounds: {format(pounds,'.2f')}, kilograms: {format(kg,'.2f')}")
return kg
}
def inchestocm(inches):
{
cm = inches * 2.54
print(f"inches: {format(inches,'.2f')}, centimeters: {format(cm,'.2f')}")
return cm
}

main.py

from conversion import *
#Import the package
class NotAValidOptionError(Exception):
{
pass
}
#Create main function to give choice of conversion
def main():
{
#Intialize the string
string = '''
1: Convert miles to km
2: Convert fahrenheit to celsius
3: Convert gallons to liters
4: Convert pounds to kg
5: Convert inches to cm'''
#Initialize the tupels
metric_name = ('miles','fahrenheit','gallons','pounds','inches')
convert_name = ('km','celsius','liters','kg','cm')
count = 3
flag = True
file1 = open("myfile.txt","a+")
#to run it 10 times
count = 10
result=0.0
while(count>=1):
{
try:
{
print(string)
choice = int(input('Which of the given conversions would you like to perform? Enter your choice from 1 to 5: '))
if choice > 5 or choice < 1:
{
raise NotAValidOptionError
}
else:
{
input_value = float(input("Enter how much {0} would you like to convert into {1}: ".format(metric_name[choice-1] , convert_name[choice-1])))
if choice == 1:
{
result = milestokm(input_value)
file1.write("Miles : " + str(input_value) + " km "+ str(result) + "\n")
}
elif choice ==2:
{
result = fahtocel(input_value)
file1.write("Fahrenheit : " + str(input_value) + " Celcius "+ str(result) + "\n")
}
elif choice == 3:
{
result = galtolit(input_value)
file1.write("Gallons : " + str(input_value) + " Litres "+ str(result) + "\n")
}
elif choice == 4:
{
result = poundstokg(input_value)
file1.write("Pounds : " + str(input_value) + " kg "+ str(result) + "\n")
}
elif choice == 5:
{
result = inchestocm(input_value)
file1.write("Inches : " + str(input_value) + " cm "+ str(result) + "\n")
}
count-=1
}
}
#user defined exception
except NotAValidOptionError:
{
print()
print("ERROR : Not a Valid Option. TRY AGAIN")
count-=1
file1.write("ERROR : Not a Valid Option. TRY AGAIN \n)")
print()
}
except ValueError:
{
print()
print("ERROR : NOT A VALID VALUE. ENTER A VALID VALUE FOR CONVERESION")
count-=1

#writing to file
file1.write("ERROR : NOT A VALID VALUE. ENTER A VALID VALUE FOR CONVERESION \n")
print()
}
}
}

#run function
main()

OUTPUT


The OUTPUT OF myfile.txt

Screenshots Of the Code (For Reference of indentation)

Conversion.py


Related Solutions

For this portion of the lab, you will reuse the Python program you wrote before. That...
For this portion of the lab, you will reuse the Python program you wrote before. That means you will open the lab you wrote in the previous assignment and change it. You should NOT start from scratch. Also, all the requirements/prohibitions from the previous lab MUST also be included /omitted from this lab.    Redesign the solution so that some portions of the code are repeated. In lab 4 you validated input to ensure that the user entered inputs within...
Description: In this program, you'll reuse the Monster data type you wrote in LA11A. Then, you'll...
Description: In this program, you'll reuse the Monster data type you wrote in LA11A. Then, you'll write a function that accepts a Monster as an argument by reference, then print the Monster to the screen. Again, this will be structured as a guided multiple choice quiz where you will choose the appropriate code for a program. After you have gotten a perfect score, write out the program and compile and run it to see it in action. Instructions: Choose the...
For this portion of Lab #2, write a program that prompts the user to enter ten...
For this portion of Lab #2, write a program that prompts the user to enter ten integer values between 1 and 100, determines the smallest and largest values entered by the user as well as the average of all the numbers entered by the user (expressed as a floating-point number), and then prints the smallest number, the largest number, and the average. Print each of these values with descriptive labels. Your program output should resemble the following (the user's input...
For this portion of the lab you will design the solution so that you perform some...
For this portion of the lab you will design the solution so that you perform some conditional tests. For this lab: 1. You will validate input to ensure that the user enters inputs within a certain range or larger than a certain minimum value. You will validate the inputs as follows: (LO 1, 2, 3) a. The user cannot enter a negative number for: i. Miles to kilometers ii. Gallons to liters iii. Pounds to kilograms iv. Inches to centimeters...
In the buffer portion of the lab, you compared how water and a buffer solution react...
In the buffer portion of the lab, you compared how water and a buffer solution react to the addition of base (NaOH) and acid (HCl). Based on your observations, which seems to have greater “buffering capacity” (ability to maintain a consistent pH): the distilled water or the buffer? The buffer solution consisted of acetic acid and sodium acetate (of which, the acetate ion is the important species). Of this mixture, the weak acid is _____ _____ and its conjugate base...
Read this entire document before beginning your lab. For this lab you are required to fulfill...
Read this entire document before beginning your lab. For this lab you are required to fulfill all requirements exactly as described in this provided document, no less, no more. Problem: Read in a word and display the requested characters from that word in the requested format. Write a Java program that ● prompts the user for a word and reads it, ● converts all characters of the input word to uppercase and display the word with a double quotation mark...
K-means clustering: a. In the k-means lab, you examined different values for k using the "knee"...
K-means clustering: a. In the k-means lab, you examined different values for k using the "knee" heuristic to pick the best value of k. Explain what is so special about the k values on the “knee”? Hint: There are two properties that together make these values of k special. b. Give an example of a type of data (data type) that k-means should not be used for and explain why.
Previously, you wrote a program named Admission for a college admissions office in which the user...
Previously, you wrote a program named Admission for a college admissions office in which the user enters a numeric high school grade point average and an admission test score. The program displays Accept or Reject based on those values. Now, create a modified program named AdmissionModularized in which the grade point average and test score are passed to a method that returns a string containing Accept or Reject. CODE: using System; using static System.Console; class Admission {    static void Main()...
Challenge: Number Stats 2 Description: Extend the program you wrote for Number Stats to determine the...
Challenge: Number Stats 2 Description: Extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. Purpose: The purpose of this challenge is to provide experience working with numerical data in a file and generating summary information including the determination of median and mode. It also provides experience adding new functionality to an existing program. Requirements: Extend the program you wrote for Number Stats to determine the median and mode...
I wrote this program to check a string is palindrome or not. but in both cases,...
I wrote this program to check a string is palindrome or not. but in both cases, it gives me palindrome. could someone help me with this program? it has an error I couldn't find. when I run the code and give a string, in both cases it gives me palindrome. for example if I give Pop it says it is a palindrome but if I give Salima, it also says palindrome. #include<string> #include <iostream> using namespace std; class PString:public string...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT