【发布时间】:2017-02-04 11:51:48
【问题描述】:
我需要一些帮助。 我试图让我的 for 循环使用小数,但我的代码不接受浮点数,我不知道下一步该做什么。谁能指出我哪里出错了?
这是一个用于将摄氏温度转换为华氏温度的代码,用户定义的步长(Delta)。这里是:
def main():
# Handshake
print("This program will convert a range of Celsius degrees to")
print("Fahrenheit degrees based on your input.")
# Ask and read low end of range
Rangelow = eval(input("Enter the low end of your range: "))
# Ask and read top end of range
Rangehigh = 1 + eval(input("Enter the high end of your range: "))
# Ask and read Delta
Delta = eval(input("Enter the Delta for your range: "))
#Display output
print("Celsius to Fahrenheit by", Delta)
for i in range(Rangelow, Rangehigh, Delta):
print(i, " ", 9/5 * i + 32)
main()
这是我的意思的一个例子:
该程序会将摄氏温度范围转换为 华氏度根据您的输入。 输入范围的低端:3.8 输入范围的高端:14.7 输入范围的 Delta:1.1 摄氏到华氏1.1 回溯(最近一次通话最后): 文件“C:\Users\jarre\Desktop\Python Programs\Conversion.py”,第 27 行,在 主要的() 文件“C:\Users\jarre\Desktop\Python Programs\Conversion.py”,第 22 行,在 main 对于范围内的 i(Rangelow,Rangehigh + 1,Delta): TypeError: 'float' 对象不能被解释为整数
我应该注意到问题似乎在于输入,在输入转换后输出没有问题抛出一个小数。
【问题讨论】:
-
当你说“我的代码不接受浮点数”时,这是什么意思?如果有追溯,请编辑您的问题并添加它。
-
查看文档:docs.python.org/2/library/functions.html...
The arguments must be plain integers. -
旁注:请不要在用户提供的输入中使用
eval。如果您期望float,则使用float而不是eval。如果您想允许int或float(或任何Python 文字),您可以使用ast.literal_eval,它可以安全地处理任意Python 文字,而不会让您执行任意代码。 -
@ShadowRanger float 只会导致错误:Traceback(最近一次调用最后一次):文件“C:\Users\jarre\Desktop\Python Programs\Conversion.py”,第 27 行,在
main() 文件“C:\Users\jarre\Desktop\Python Programs\Conversion.py”,第 22 行,在 main for i in range(Rangelow, Rangehigh + 1, Delta): TypeError: 'float' object cannot be解释为整数 -
@Jarbcd:这是一个旁注是有原因的。使用
float是您可能接受的示例,如果您的代码的其余部分预期floats(它没有,因为range仅支持int)。关键是eval不安全/不稳定,您应该使用更具体的东西来满足您的需求。如果你想要float(这里可能是个坏主意;如果你真的想允许小数,你会想要decimal.Decimal进行无损存储并使用AChampion 的decimal_range函数),使用float。如果你想要int,请使用int。如果您想要任何旧的 Python 文字,请使用ast.literal_eval。
标签: python-3.x for-loop range user-input