Making a collatz program automate the boring stuff

前端 未结 25 2284
一整个雨季
一整个雨季 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:37

    Nuncjo got the solution that works. I tweaked it a little to add try and except statements for error handling.

    def collatz(number):
        if number % 2 == 0:
            print(number // 2)
            return number // 2
    
        elif number % 2 == 1:
            result = 3 * number + 1
            print(result)
            return result
    
    try:
        n = input("Enter number: ")
        while n > 0 and n!= 1:
            n = collatz(int(n))
    except ValueError:
        print('whoops, type an integer, bro.')
    

提交回复
热议问题