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.

Paxxer
  • 21
  • 3
  • What do you want to happen while `n` is 1? – mkrieger1 Apr 19 '22 at 22:49
  • I want the process to start completely over, start the cycle all over again until sys.exit – Paxxer Apr 19 '22 at 22:51
  • If I understand correctly, you could put the two lines making up the `while n != 1` loop *inside* an endless loop written as `while True`. – mkrieger1 Apr 19 '22 at 22:52
  • perhaps, I just wrote it as while `n` is 1 because while `n` is not one is how I started the operation. I am just looking to start the "Give me a number: " cycle once the collatz system has finished computing instead of >>> – Paxxer Apr 19 '22 at 22:57
  • See https://stackoverflow.com/questions/65764302/python-i-want-to-repeat-a-function-indefinitely for an example – mkrieger1 Apr 19 '22 at 22:58
  • That is the perfect link and question! If only it was easier to find! Thanks for your time! – Paxxer Apr 19 '22 at 23:02

1 Answers1

0

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.

Paxxer
  • 21
  • 3