首页 > 解决方案 > 在python中将英寸的输入转换为立方英寸

问题描述

这是我得到的,但转换不起作用

a = input('What is your name? ') 
b = input('What is the color of the ball? ')
c= input('What is the radius of the ball in inches? ').split()[:2]
converted_data = float=(c) * {'in': 2.54, 'cm': 0.39}[unit] 
print('Hello ' + a + ', the ball is ' + b + ' and has a volume of ' + converted_data + ' cubic inches.')

标签: python

解决方案


我喜欢您制作字典以保存适当的单位转换值的做法。在您的代码中,您需要为变量分配一个值unit

如果cm? _

最后,要计算volumegiven radius,首先将(如您所想)转换为以英寸为单位的半径,如果需要,然后应用适当的公式。

c, unit = input("What is the radius of the ball? (e.g. '4 in' or '3.14cm') ").split()[:2]
radius = float(c) * {'in': 1, 'cm': 0.3937}[unit]
volume = 4/3 * math.pi * radius**2
print('Hello ' + a + ', the ball is ' + b + ' and has a volume of ' + volume + ' in³.')

推荐阅读