python - Python 的问题:使用 round() 函数时,“TypeError: 'str' object not callable”,值是 FLOAT 变量
问题描述
我对 Python 很陌生,刚刚学习了基本的条件和逻辑运算符。我目前正在从事一个项目,该项目采用用户的重量并将其转换为公斤,如果它以磅为单位,或者如果它以公斤为单位,则转换为磅,具体取决于用户输入。
当我测试我的程序时,控制台吐出一个错误:
我仔细检查了我的代码,并且正在舍入一个存储浮点值的变量。它不是字符串,所以我不知道为什么会出现此错误。我尝试更改变量名并重置,但这些都没有帮助。我在这里错过了一些非常明显的东西吗?如果是的话,我深表歉意,我对 Python 和一般编程仍然很陌生,但想精通它。这是我的源代码:
import sys
un_weight = int((input("Weight: ")))
value = input("Is your weight in (L)bs or (K)g: ")
if (value == "K") or (value == "k"):
conv = un_weight * 2.2
elif (value == "L") or (value == "l"):
conv = un_weight / 2.2
else:
print("That weight type does not exist. Please try again.")
round = input("Do you want your number rounded? (Y/N): ")
if (round == "Y") or (round == "y") or (round == "Yes") or (round == "yes"):
print("Rounding Number... ")
weight = round(conv)
round_op = True
elif (round == "N") or (round == "n") or (round == "No") or (round == "no"):
print("Rounding operation terminated. Calculating decimal weight...")
round_op = False
else:
print("That is not a valid answer. Please try again.")
exit()
if (value == "K") or (value == "k") and not round_op:
print(f"Your weight is {conv} Lbs.")
elif (value == "L") or (value == "l") and not round_op:
print(f"Your weight is {conv} Kg.")
elif (value == "K") or (value == "k") and round_op:
print(f"Your rounded weight is about {weight} Lbs.")
elif (value == "L") or (value == "l") and round_op:
print(f"Your rounded weight is about {weight} Kg.")
else:
print("Error: Operation failed. Please try again later.")
exit()
如您所见,该un_weight
变量立即使用该函数转换为整数int()
,所以我不知道为什么 Python 认为它是一个字符串(如果这就是它所说的)。请原谅这个愚蠢的问题;我只想知道这背后的原因。我在这里先向您的帮助表示感谢。
解决方案
问题在这里:
round = input("Do you want your number rounded? (Y/N): ")
您已将round()
函数替换为包含输入字符串的变量。
不要使用与内置函数相同的变量名。只能命名一件事round
——如果它是你的字符串,那么它就不是数学函数。
推荐阅读
- sapui5 - 如何使一组切换按钮响应
- git - GitHub中的命令上传和浏览器上传有什么区别?
- php - magento 重写模型混淆
- android - 滚动时如何在没有 UI 滞后的情况下更新 RecyclerView 内容?
- google-analytics - GA Page View 跟踪以及其他信息
- java - 如何使用 java.util.Scanner 类读取输入?
- react-native - FlatList 可触摸不透明度在 Android 上不起作用
- python - 更新图无效组件道具图时出错
- blazor - Blazor WebAssembly App 可以用于生产吗?
- angular - Jasmin:如何在 Angular 8 中模拟 @ViewChild 组件