pythoncollatz

Writing a collatz program, wish to repeat process while n == 1


I am working my way through the Boring python book and have no previous experience with coding at all. I have just worked on a collatz system and I am curious as to how to loop the system indefinitely. Attached is the coding I have so far.

def collatz(number):
    if number % 2 == 0:
        result1 = number // 2
        print(result1)
        return result1
    elif number % 2 == 1:
        result2 = 3 * number + 1
        print(result2)
        return result2
n = input('Give me a number: ')
while n != 1:
    n = collatz(int(n))
while n == 1:
    ~~~

I am curious as to what to put in the ~~~ to achieve this loop.


Solution

  • Okay, I reviewed the link mentioned in the comments, and realized that a while True loop would be the smart solution. That being said, I wanted to see if I could somehow build off of what I already had built, and solved my question with the following code:

    def collatz(number):
        if number % 2 == 0:
            result1 = number // 2
            print(result1)
            return result1
        elif number % 2 == 1:
            result2 = 3 * number + 1
            print(result2)
            return result2
    n = input('Give me a number: ')
    while n != 1:
        n = collatz(int(n))
    while n == 1:
        n = input('Give me a number: ')
        while n != 1:
            n = collatz(int(n))
    

    I understand that this is not the most compact or efficient answer, but it was made to fit the design that I had already built. If I were to have this be a professional project, I would have used the condensed version, that being said I learned more about the art of Python tinkering with this until it worked.