0

How do I make it so that the program will loop after the user enters a non integer value in it?

I already tried to use "while int(u) != int"

u = raw_input("enter a positive number")
while u != int:
    u = raw_input("Please enter a number")
if u == int:
    print "that's a number"
  • use `try` and `except` – furas Apr 15 '19 at 02:09
  • Is there any reason you're using Python 2? Also, I think you want `isinstance(u, int)`. – gmds Apr 15 '19 at 02:11
  • @gmds `raw_input` gives string so `isinstance(u, int)` will give `False`. You have to try to convert to integer - using `int(u)` - to check if it is string with integer value. And `int(u)` may get error `ValueError` which you can catch with `try/except` – furas Apr 15 '19 at 02:13
  • @furas Yes, my mistake, I meant `.isdigit()`. – gmds Apr 15 '19 at 02:21

2 Answers2

1

Try and cast it as a type and catch the exception if it isn't

while True:
    u = raw_input("Enter a positive number: ")
    try:
        num = int(u)
    except ValueError:
        print "{} is not a number".format(u)
        continue
    break
print "{} is a number".format(num)

This only checks to make sure it is an integer, not if it is a positive number, but that should be easy to add.

dwagon
  • 501
  • 3
  • 9
0

You forgot about .isdigit():

while True:
    u = raw_input("Enter a positive number: ")
    if not u.isdigit():
        print u, "is not a number"
        continue
    u = int(u)
print u, "is a number"

Example output:

Enter a positive number: sf
sf is not a number
Enter a positive number: 1
1 is a number
U13-Forward
  • 69,221
  • 14
  • 89
  • 114