1
Fahr = input("Insert temperature in Fahrenheit: " ) 

while type(Fahr) != float or type(Fahr) != int:

    Fahr = input("Error: Insert temperature in Fahrenheit: " )

Celcius = ((Fahr) - 32) * 5/9


print("Your imput: " + Fahr + " Fahrenheit" ) 

print("This is equal to: " + Celcius + " Celcius" )

I need to be sure that the user only inserts INT's or floats. When i execute this code, it goes automatically go in the while loop even when i insert an INT or float. Whats wrong with this code and how should it be?

M.Ince
  • 19
  • 5
  • 1
    `Fahr` will always be a string (`str`), that's what `input()` returns. – cdarke Sep 22 '16 at 16:03
  • read this: http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – proton Sep 22 '16 at 16:04
  • Or this: http://stackoverflow.com/questions/14566260/inputing-floats-integers-or-equations-in-raw-input-to-define-a-variable – cdarke Sep 22 '16 at 16:05
  • I believe the solution is to use the `and` operator instead of the `or` operator. A number can't be both an integer and a float at the same time. – Fernando Karpinski Sep 22 '16 at 16:06
  • 1
    Is this Python 2 or Python 3? `input()` has different functionality between the two, I was assuming python 3. – cdarke Sep 22 '16 at 16:10
  • @cdarke, this is Python 3. I tested with Python 2, so maybe I was wrong. i updated my comment. – Fernando Karpinski Sep 22 '16 at 16:11

2 Answers2

0

Could you try with the following code:

def inp():
    try:
        Fahr = float(raw_input("Insert temperature in Fahrenheit: " ))
        return Fahr
    except Exception as e:
        return e

Fahr = inp()
while True:
    if 'could not convert' in str(Fahr):
        Fahr = inp()
    else:
        break

Celcius = ((Fahr) - 32) * 5/float(9)

print("Your input: " + str(Fahr) + " Fahrenheit" ) 
print("This is equal to: " + str(Celcius) + " Celcius" )

The following is the output:

>>> ================================ RESTART ================================
>>> 
Insert temperature in Fahrenheit: hello
Insert temperature in Fahrenheit: !@
Insert temperature in Fahrenheit: ()()((
Insert temperature in Fahrenheit: 10.5
Your input: 10.5 Fahrenheit
This is equal to: -11.9444444444 Celcius
Jeril
  • 7,858
  • 3
  • 52
  • 69
-1

input() function always return a string. Convert to int or float first.

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
Jal
  • 205
  • 1
  • 2
  • 8
  • Fahr = int(input("Insert temperature in Fahrenheit: " )) . I did this now but when i type a string it gives me: invalid literal for int() with base 10: 'df' – M.Ince Sep 22 '16 at 16:06
  • That is normal. You can catch this exception and retry the input in that case – 3Doubloons Sep 22 '16 at 16:09
  • This answer doesn't include anything to ensure that the user enters a number, which the OP requires. – TigerhawkT3 Sep 22 '16 at 16:15