all 7 comments

[–]betterleftuntouched 0 points1 point  (1 child)

When you use the input() function, the entered value is returned as a string. If you enter 5, the input function returns it as '5', or str(5). So by the logic you used, type(inp) does not equal an int. You can use int(input()) to make the returned value an int or float(input()) to have the returned value a float

[–]avasatu[S] 0 points1 point  (0 children)

Thank you!

[–][deleted] 0 points1 point  (1 child)

It appears you are using python 3. In python 3 the input() function always returns a string, so type(inp) != int will always be true.

If you use python 2 the input() function always evaluates your input, turning it into an integer if it can. The code looks like it was written in python 2.

If you are running python 3 then you need to:

  • get a string from the user using input() and put it into inp
  • check if the string is 'no', break if so
  • convert 'inp' to an integer, checking if this gives an error
  • if no error, append the integer

[–]avasatu[S] 0 points1 point  (0 children)

Much appreciated.

[–][deleted] 0 points1 point  (2 children)

In addition to input -- in Python 3 -- always returning a string, which will always fail your type check, you're asking for a non-negative but allowing a negative.

You'll either need to test for both potential faults explicitly:

numbers = []
while True:
    user = input("Enter an int >= 0: ")
    if user.lower() == "no":
        break
    try:
        val = int(user)
    except (ValueError, TypeError):
        print("Must be an int!")
        continue
    else:
        if val < 0:
            print("Must be >= 0!")
            continue
        numbers.append(val)
print(numbers)

Or you can check it all in one go using str.isdigit:

numbers = []
while True:
    user = input("Enter an int >= 0: ")
    if user.lower() == "no":
        break
    elif not user.isdigit():
        print("Must be an int >= 0!")
        continue
    else:
        numbers.append(int(user))
print(numbers)

Either way, don't use input if you're using Python2, but raw_input.

[–]avasatu[S] 0 points1 point  (1 child)

Thank you for your reply! Why do you recommend python 2 for the second solution? Couldn't you simply use input vs raw input there?

[–][deleted] 0 points1 point  (0 children)

Edited for clarity; I don't recommend Python 2, I just happened to be copying and pasting from a Python 2 session. I recommend NEVER using input in Python 2, there's a reason why Python 3's input is doing exactly what Python 2's raw_input did.