你能在这个 for 循环中使用浮点数吗?

Jar*_*bcd 2 for-loop user-input range python-3.x

我需要帮助。我试图让我的 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()
Run Code Online (Sandbox Code Playgroud)

这是我的意思的一个例子:

该程序将根据您的输入将一系列摄氏度转换为华氏度。输入范围的低端:3.8 输入范围的高端:14.7 输入范围的 Delta:1.1 摄氏度到华氏度 by 1.1 Traceback(最近一次调用最后一次):文件“C:\Users\jarre\Desktop\ Python Programs\Conversion.py", line 27, in main() 文件 "C:\Users\jarre\Desktop\Python Programs\Conversion.py", line 22, in main for i in range(Rangelow, Rangehigh + 1, Delta): TypeError: 'float' 对象不能解释为整数

我应该注意到问题似乎出在输入上,在输入转换后,输出没有问题抛出小数。

ACh*_*ion 5

您不能使用内置来进行浮点数/十进制增量,但构建自己的生成器相当容易:

def decimal_range(start, stop, increment):
    while start < stop: # and not math.isclose(start, stop): Py>3.5
        yield start
        start += increment

for i in decimal_range(Rangelow, Rangehigh, Delta):
    ...
Run Code Online (Sandbox Code Playgroud)

或者你可以使用,numpy但这感觉就像一把敲碎坚果的大锤:

import numpy as np
for i in np.arange(Rangelow, Rangehigh, Delta):
    ...
Run Code Online (Sandbox Code Playgroud)