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.
The arguments must be plain integers.
– Thrusheval
on user supplied input. If you expectfloat
, then usefloat
instead ofeval
. If you want to allowint
orfloat
(or any Python literal), you can useast.literal_eval
, which will safely handle arbitrary Python literals without opening you up to executing arbitrary code. – Autoicousfloat
is an example of what you might accept if the rest of your code expectedfloat
s (it doesn't, becauserange
only supportsint
). The point is thateval
is unsafe/unstable, and you should be using something more specific to what you want. If you wantfloat
(probably a bad idea here; if you really want to allow decimals, you'd wantdecimal.Decimal
for lossless storage and use AChampion'sdecimal_range
function with it), usefloat
. If you wantint
, useint
. If you want any old Python literal, useast.literal_eval
. – Autoicousrange
I should usefloat
? ordecimal.Decimal
? (I've only just started coding, btw) How would I implement that? I'd bet it's not just as simple as replacingrange
withdecimal.Decimal
Or would it maybe be as simple as using the code that AChampion wrote as it is? – Vulgarfloat
oreval
you'd usedecimal.Decimal
. Instead ofrange
, you'd use AChampion'sdecimal_range
function. – Autoicous