Making a collatz program automate the boring stuff

前端 未结 25 2142
一整个雨季
一整个雨季 2020-12-08 11:14

I\'m trying to write a Collatz program using the guidelines from a project found at the end of chapter 3 of Automate the Boring Stuff with Python. I\'m using python 3.

25条回答
  •  囚心锁ツ
    2020-12-08 11:53

    def collatz(number):
        while number != 1:
            if number % 2 == 0:
                number = number // 2
                print(number)
    
            elif number % 2 == 1:
                number = number * 3 + 1
                print(number)
    
    try:
        num = int(input())
        collatz(num)
    except ValueError:
        print('Please use whole numbers only.')
    

    This is what I came up with on my own and based solely on what I've learned from the book so far. It took me a little bit but one of the tools I used that was invaluable to me finding my solution and has also been invaluable in learning this content is the python visualizer tool at: http://www.pythontutor.com/visualize.html#mode=edit

    I was able to see what my code was doing and where it was getting hung up and I was able to continually make tweaks until I got it right.

提交回复
热议问题