[Tutor] How to separate UI code from program logic?

Alan Gauld alan.gauld at yahoo.co.uk
Sun May 6 18:05:28 EDT 2018

```
On 6 May 2018, at 23:00, boB Stepp <robertvstepp at gmail.com> wrote:

>I was solving a programming problem in one of my books concerning the
>generation of a Collatz sequence
>(https://en.wikipedia.org/wiki/Collatz_conjecture), and started to
>wonder how I should separate my program's output from its logic.  It
>seems like this should be obvious to me, but, unfortunately, it isn't.
>The core functions from my program are:
>#----------------------------------------------------------------------------
>def collatz(integer):
>    """Returns the Collatz sequence number corresponding to integer.  integer
>    must be > 0, or the sequence will not converge to 1."""
>    if integer % 2 == 0:
>        return integer // 2
>    else:
>        return 3 * integer + 1
>def generate_collatz_sequence(seed):
>    """Generates a Collatz sequence starting from seed.
>    seed must be a positive integer, or the sequence will not
>    coverge to 1."""
>    counter = 0
>    collatz_number = seed
>    print("Collatz seed number: ", collatz_number)
>    while True:
>        counter += 1
>        collatz_number = collatz(collatz_number)
>        print("Collatz number", counter, ": ", collatz_number)
>        if collatz_number == 1:
>            print("The Collatz sequence has once again converged to 1!")
>            break
>#----------------------------------------------------------------------------
>My understanding of best practice here is that I should not have any
>print() calls inside my generate_collatz_sequence() function.  I
>_could_ store the generated sequence in a list and return it, but that
>does not seem like good use of RAM if some user-supplied seed value
>led to kazillions of Collatz sequence numbers being generated.

The clue is in that last word.
Write a generator function that yields the intermediate results.

Alan g.
```