Collatz Function: Strange try/except Bugs

49 views Asked by At

So I'm getting into coding and I was doing an exercise from the Automate the Boring Stuff book. I figured out how to write the original function, but then I wanted to try to add a little more to it and see if I could fit it all in one function.

So in Python 3.6.2, this code works fine if I enter strings, positive integers, nothing, or entering "quit". However, if I enter 1 at any point between the others then try "quitting", it doesn't quit until I enter "quit" as many times as I previously entered 1. (like I have to cancel them out).

If I enter 0 or any int < 0, I get a different problem where if I then try to "quit" it prints 0, then "Enter a POSITIVE integer!".

Can't post pics since I just joined, but heres a link: https://i.stack.imgur.com/a68G8.jpg

I couldn't find anything about this specific issue on similar posts and I'm not too worried about this working the way it is, but I'm really curious about what exactly the computer is doing.

Can someone explain this to me?

def collatz():
    number = input('Enter a positive integer: ')
    try:
        while number != 1:
            number = int(number) #If value is not int in next lines, execpt.
            if number <= 0:
                print('I said to enter a POSITIVE integer!')
                collatz()
            if number == 1:
                print('How about another number?')
                collatz()
            elif number % 2 == 0:  #Checks if even number
                number = number // 2
                print(number)
            else:                  #For odd numbers
                number = number * 3 + 1  
                print(number)

        print('Cool, huh? Try another, or type "quit" to exit.')
        collatz()

    except:
        if str(number) == 'quit':
            quit
        else:
            print('Enter an INTEGER!')
            collatz()


collatz()
0

There are 0 answers