什么是“不支持/:'str'和'float'的操作数类型”

2024-04-26 23:41:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道为什么我的代码不起作用。 这是我的密码:

# Chapter 1 Problem 2

distance = input("Enter a distance in kilometers:  ")

print ("You entered ")
print (distance, "km") 
print ("Which is equivalent to ")
print (distance / 1.61) 

错误是:

"TypeError: unsupported operand type(s) for /: 'str' and 'float'"

我知道这是因为除法,但我不知道如何将我的输入除以1.61。你知道吗


Tags: 代码inyou密码whichinputisdistance
1条回答
网友
1楼 · 发布于 2024-04-26 23:41:00

试试这个:

distance = float(input("Enter a distance in kilometers:  "))

print ("You entered ")
print (distance, "km") 
print ("Which is equivalent to ")
print (distance / 1.61)

input返回字符串值,因为您正在执行float除法,所以两个操作数都必须是float。因此,我们将输入值转换为float。你知道吗

相关问题 更多 >