厘米到英寸转换程序Python
你好,我正在尝试做一个转换程序,但我不能让它工作,我要转换成倍不同的东西,但我开始厘米英寸。我得到错误类型错误:/:'str'和'float'的操作数类型不受支持。 下面是一些代码:厘米到英寸转换程序Python,python,Python,你好,我正在尝试做一个转换程序,但我不能让它工作,我要转换成倍不同的东西,但我开始厘米英寸。我得到错误类型错误:/:'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('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')
%s是格式化字符串的符号,%f应用于浮点数。但是,在较新版本的python中,应该使用{0}
print('There are {0}'.format(number / inch))
请阅读以了解更多有关此的信息
此外,正如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”的引号。问题在于
number
是一个字符串,您无法对其执行数学运算。您需要做的是使用int(number)
或float(number)
将其转换为整数或浮点。
所以你可以做:
print(“有℅格式(float(number)/inch))
这里是现在的代码number=float(input())inch=float(2.54)如果number='1':print('多少英寸?'))print('have are{0})。格式(number/inch')仍在获取某些操作数错误reason@C9Fox检查编辑;现在需要删除if语句上的引号。即:如果数字==1: