gpt4 book ai didi

python - CM 到 INCH 转换程序 Python

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:19 25 4
gpt4 key购买 nike

你好,我正在尝试制作一个转换程序,但我无法让它工作,我将转换多种不同的东西,但我从 CM 开始到 INCH。我收到错误 TypeError: unsupported operand type(s) for/: 'str' and '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')

最佳答案

%s 是格式化字符串的表示法,%f 应该用于 float 。但是,在较新版本的 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”的引号。

关于python - CM 到 INCH 转换程序 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38985615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com