Unit conversion Write a unit conversion program that asks the users from which unit they want to convert fl oz gal oz lb in ft mi and to which unit they want to convert ml l g kg mm cm m km Reject inc
Solution:
unit_conversion.py
# Unit Conversion Program
# Conversion factors
conversion_factors = {
'fl. oz': {
'ml': 29.5735,
'l': 0.0295735
},
'gal': {
'ml': 3785.41,
'l': 3.78541
},
'oz': {
'g': 28.3495,
'kg': 0.0283495
},
'lb': {
'g': 453.592,
'kg': 0.453592
},
'in': {
'mm': 25.4,
'cm': 2.54,
'm': 0.0254,
'km': 0.0000254
},
'ft': {
'mm': 304.8,
'cm': 30.48,
'm': 0.3048,
'km': 0.0003048
},
'mi': {
'mm': 1609344,
'cm': 160934.4,
'm': 1609.344,
'km': 1.609344
}
}
# Get user input
from_unit = input('Convert from? ')
to_unit = input('Convert to? ')
value = float(input('Value? '))
# Check if conversion is possible
if from_unit not in conversion_factors or to_unit not in conversion_factors[from_unit]:
print('Conversion not possible.')
else:
# Perform conversion
factor = conversion_factors[from_unit][to_unit]
result = value * factor
# Print result
print(f'{value} {from_unit} = {result} {to_unit}')
Sample Output:
Convert from? gal
Convert to? ml
Value? 2.5
2.5 gal = 9463.525 ml
原文地址: https://www.cveoy.top/t/topic/boY3 著作权归作者所有。请勿转载和采集!