-2

I'm learning Python, and I wrote a simple script that creates a list of tasks I need to do today. After putting an input on the task to be done, I have the script ask how long it will take to do that task. It would work in adding the float to a variable called "totaltime" but if you entered a word, it would crash, so I created an if else statement looking for if the user entered an integer and float and if they didn't, have them repeat the process. For some reason when I run it, it can't see if the input is a float or integer, it just moves on the else statement and repeats it. Please help! I've been scouring the internet and can't find a solution. I added the issue part of the script so that's its easier to read (and the totaltime variable)

totaltime = float()

    while True:
        print("How long will this task take?")          
        new_time = input("> ")

    if new_time == int or new_time == float:
        totaltime = float(totaltime) + float(new_time)
        break

    else: 
        print("You must enter a valid number, written as (H.M).")
Eliot S Winchell
  • 368
  • 1
  • 6
  • 19
  • 1
    (More discussions on type checking in Python, how to do it, and whether it's necessary at all http://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python ) – TessellatingHeckler Jun 21 '15 at 02:47

1 Answers1

0

Instead of checking type, you should just do the conversion in a try/except block.

totaltime = 0.0

while True:
    try:     
        new_time = float(input("How long will this task take?\n> "))
        totaltime += new_time
        break
    except ValueError:
        print("You must enter a valid number, written as (H.M).")

Your attempt to check type is flawed anyway. The return value from input will always be string.

If you did want to check type, you should use isinstance

e.g.

if isinstance(new_time, (int, float)):

But your code is actually testing the type int or float against the value of new_time. Which will always be wrong.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • thank you! I forgot about the try statement... excellent answer! May I ask, what is the difference between "new_time = float(new_time)" and "new_time=float()" like I'm not sure why you plug the variable back in, is that required? – Eliot S Winchell Jun 21 '15 at 02:56
  • When using `new_time = float(new_time)`, `new_time` starts out life a string with the value you input (e.g. "2.5"). Calling `float` converts it to a float and assigns it back to the same variable. `new_time=float()` just creates a float variable, which by default is assigned the value 0.0. – Paul Rooney Jun 21 '15 at 03:00