1

as part of the Chapter 3 exercise for Automate the Boring Stuff, I need to write a short program that mimics the Collatz sequence, where:

  • If number inputted is even number, divide it by 2, repeat until it equals 1;
  • If number inputted is odd number, multiply it by 3 then plus 1, repeat until it equals 1;
  • Create a clean exit for Ctrl+C.
  • Detect whether the user typed in a noninteger string.

Below is my code so far, which seems to work but I would appreciate any advice/best practice for improving it.

My main question is, after the program prints 'Enter integers only', is there any short and simple way to loop back to the 'Enter any number: ' line? I can't think of anything atm besides complicated if loops. Thanks.

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

try: 
    entry = input('Enter any number : ')
    number = int(entry)
    print(number)
    collatz(number)
except ValueError:
    print('Enter integers only.')
except KeyboardInterrupt:
    sys.end()
3
  • Warning: DO NOT use a recursive function when calculating Collatz numbers: given the right number, you'd get millions or recursion. Just try with 27 :) Commented Jun 13, 2022 at 10:39
  • Which part of it is a recursive function? I tried 27 with the code and it seems to work fine and not too many lines. Sorry I'm a beginner so can't really tell. Commented Jun 13, 2022 at 11:42
  • I suggested 27 because it takes more than one hundred steps to be solved, which can be surprising for such a small number. But there are larger numbers which literally require millions of steps, so you will get a "recursion depth exceeded" error. Your function is recursive because it calls itself - that's what recursion means Commented Jun 13, 2022 at 12:36

4 Answers 4

1

You can try using a while loop. The below code will be helpful for you.

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

while True:
    try: 
        entry = input('Enter any number : ')
        number = int(entry)
        print(number)
        collatz(number)
    except ValueError:
        print('Enter integers only.')
    except KeyboardInterrupt:
        break # Stop the while loop.
        sys.end()
Sign up to request clarification or add additional context in comments.

Comments

0

As you want to keep prompting the same, until the program exits. I'd suggest just encapsulating the program code in a while(true) loop:

while True:
    try: 
        entry = input('Enter any number : ')
        number = int(entry)
        print(number)
        collatz(number)
    except ValueError:
        print('Enter integers only.')
    except KeyboardInterrupt:
        sys.end()

2 Comments

just quick sidenote, true shouldn't be in brackets and should have a capitalised "t".
@AnonyMous woops, thanks for the heads-up. It's still early here :)
0

You can define an iteration to make sure the input is integer type.

while True: # executes the loop body indefinitely
    try: 
        entry = input('Enter any number : ')
        number = int(entry)
        print(number)
        collatz(number)
        break  # immediately terminates the loop entirely
    except ValueError:
        print('Enter integers only.')
    except KeyboardInterrupt:
        sys.end()

Comments

0

Put it in a "while" loop.

while True:
    try:
        ...
    except:
        ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.