Can you use float numbers in this for loop?

Issue

I need some help.
I’m trying to make my for loop work with decimals, but my code won’t accept floats and I’m not sure what to do next. Can anyone point out where I went wrong?

It’s a code used for converting Celsius to Fahrenheit in steps (Delta) that the user defines. Here it is:

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()

This is an example of what I mean:

This program will convert a range of Celsius degrees to
Fahrenheit degrees based on your input.
Enter the low end of your range: 3.8
Enter the high end of your range: 14.7
Enter the Delta for your range: 1.1
Celsius to Fahrenheit by 1.1
Traceback (most recent call last):
File “C:\Users\jarre\Desktop\Python Programs\Conversion.py”, line 27, in
main()
File “C:\Users\jarre\Desktop\Python Programs\Conversion.py”, line 22, in main
for i in range(Rangelow, Rangehigh + 1, Delta):
TypeError: ‘float’ object cannot be interpreted as an integer

I should note that the problem seems to lie with the input, the output has no issue throwing out a decimal after the input has been converted.

Solution

You can’t use the built in to do float/decimal increments but it is fairly easy to construct your own generator:

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):
    ...

Or you could use numpy but this feels like a sledgehammer cracking a nut:

import numpy as np
for i in np.arange(Rangelow, Rangehigh, Delta):
    ...

Answered By – AChampion

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.