Python try / except with Collatz sequence

I am trying to write a Collatz sequence when adding try and except statement to determine if the user is entering a noninteger in the string, and I cannot figure out how to do this. If you read Try / Except in Python: how do you properly ignore Exceptions? but I am still at a loss. My code is:

def collatz(y):
    try:
        if y % 2 == 0:
            print(int(y/2))
            return int(y/2)

        else:
            print(int(y*3+1))
            return int(y*3 +1)

    except ValueError:  
        print('Error: Invalid Value, the program should take in integers.')

print('Please enter a number and the Collatz sequence will be printed')
x = int(input())

while x != 1:
    x = collatz(x)
+4
source share
1 answer

In the case of non-integer input, the program will fail before you call collatz()with the code as you wrote it, which means that your block trywill not catch the exception:

def collatz(y):
    try:
        if y % 2 == 0:
            print(int(y/2))
            return int(y/2)

        else:
            print(int(y*3+1))
            return int(y*3 +1)

    except ValueError:  
        print('Error: Invalid Value, the program should take in integers.')

print('Please enter a number and the Collatz sequence will be printed')
x = int(input())  # <-- THIS throws ValueError if input is non integer...

while x != 1:
    x = collatz(x)  # <-- ...but your try/except is in here.

try/except. collatz():

def collatz(y):
    if y % 2 == 0:
        print(int(y/2))
        return int(y/2)
    else:
        print(int(y*3+1))
        return int(y*3 +1)


print('Please enter a number and the Collatz sequence will be printed')
try:
    x = int(input())
except ValueError:  
    print('Error: Invalid Value, the program should take in integers.')
    exit()

while x != 1:
    x = collatz(x)
+2

Source: https://habr.com/ru/post/1620809/


All Articles