2

I'm learning python, and am stuck on a project. The main part of the project was to code the collatz sequence, which wasn't a problem. The next part is to validate the user input using try and except, in order to make sure only an integer value is given in. So far, I have the following code:

def collatz(number):
    if number % 2 == 0:
        return number // 2
    elif number % 2 == 1:
        return (3*number) + 1


print('Please enter a number:')
number = ''
try:
    number = int(input())
except ValueError:
    print('Incorrect type of data entered.\nPlease enter an integer!')
    while number is not int:
        try:
            number = int(input())
        except ValueError:
            print('Incorrect type of data entered.\nPlease enter an integer!')

output = number

while output != 1:
    output = collatz(output)
    print(output)

My problem is I'm not sure how to repeat the try/except statement until I get an integer from the user. Right now, if I enter a string instead of an integer, the program goes into a loop and entering an integer subsequently does not help. I read quite a few threads on the topic, but they didn't shed light as to the aforementioned problem.

Would really like to understand where I'm going wrong.

sar91
  • 125
  • 1
  • 4
  • I't fine if you check only 3 times if the given number is an integer. you can check the type with `isinstance` function – user1767754 Oct 02 '17 at 17:09
  • 1
    `number is not int` is not ever going to be true. `type(number) is not int` would work, but better to use `not isinstance(number, int)`. Better still: just use `while True: and `break` out when no exception is raised. – Martijn Pieters Oct 02 '17 at 17:11
  • You're of course right. That was a very silly mistake on my part, I missed out on the type(). I'll check out is instance(number, int) - I'm not aware of the function. But thanks a lot for the tips!! Very much appreciated. – sar91 Oct 02 '17 at 21:18

2 Answers2

1

You can use:

valid=False
while not valid:
    try:
        number=int(input())
        valid=True
    except ValueError:
        print('Incorrect type of data entered.\nPlease enter an integer!')
MegaIng
  • 7,361
  • 1
  • 22
  • 35
0

Just use isinstance(x, int), where x is input.

It returns True if x is an int. Just another solution, in case you were looking for a different way!

codeninja
  • 92
  • 1
  • 10
  • Thanks for the comment, I'll check out the isinstance function - I wasn't aware of it until now. Thanks for the tip!! – sar91 Oct 02 '17 at 21:20