Making a collatz program automate the boring stuff

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

    My 17 lines of code for the same exercise that I have came up with.

        def collatz(number):
        """ check if the number is even or odd and performs calculations.
        """
        if number % 2  == 0: # even
            print(number // 2)
            return number //2
        elif number % 2 != 0: # odd 
            result = 3*number+1
            print(result)
            return result
    
    try:
        n = input('Enter number: ') # takes user input
        while n !=1: # performs while loop until 'n' becomes 1
            n = collatz(int(n)) # passes 'n' to collatz() function until it arrives at '1'
    except ValueError:
        print('Value Error. Please enter integer.')
    

提交回复
热议问题