您好我正在尝试制作转换程序,但我无法让它工作,我将转换多种不同的东西,但我从CM开始到INCH。我得到错误TypeError:/|'str'和'float'的不支持的操作数类型。 以下是一些代码:
print('Press the number of the one you want to convert: ')
number = input()
inch = float(2.54)
if number == '1':
print('How many inch? ')
print('There are %s'.format(number / inch))
Here is the whole code:
print('Welcome to the converting program')
print('What of these do you want to convert?')
print( "\nHow many centimeters in inches? 1"
"\nHow many milliliters in a pint? 2"
"\nHow many acres in a square-mile? 3"
"\nHow many pounds in a metric ton? 4"
"\nHow many calories in a BTU? 5")
print('Press the number of the one you want to convert: ')
number = float(input())
inch = float(2.54)
if number == '1':
print('How many inch? ')
print('There are {0}'.format(number / inch))
elif number == '2':
print('millimeters')
elif number == '3':
print('acres')
elif number == '4':
print('pounds')
elif number == '5':
print('calories')
答案 0 :(得分:1)
%s是格式化字符串的表示法,%f应该用于浮点数。在较新版本的python中,您应该使用{0}
print('There are {0}'.format(number / inch))
阅读PEP 3101了解更多相关信息。
除此之外,正如Sebastian Hietsch在他的回答中提到的,你的输入变量是一个需要首先转换为浮点数的字符串。在格式化表达式之前执行此操作。
number = float(input())
inch = float(2.54)
您可能想要添加一些错误处理:
try:
number = float(input())
except TypeError as e:
print('input must be a float')
inch = float(2.54)
当然,您需要删除if语句中“1”的引号。
答案 1 :(得分:0)
问题是number
是一个字符串,你不能对它进行数学运算。您需要做的是使用int(number)
或float(number)
将其转换为整数或浮点数。
所以你可以这样做:print("There are ℅f".format(float(number)/inch))