Making a collatz program automate the boring stuff

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

    def collatz(number):
        if number % 2 == 0:  # Even number
            return number // 2
    
        elif number % 2 == 1:  # Odd number
            return number * 3 + 1
    
    print('Please enter a number') # Ask for the number
    
    
    # Check if the number is an integer, if so, see if even or odd. If not, rebuke and exit
    try:
        number = int(input())
        while number != 1:
            collatz(number)
            print(number)
            number = collatz(number)
        else:
            print('You Win. The number is now 1!')
    except ValueError:
         print('Please enter an integer')
    

    This is what I came up with for this practice exercise. It asks for an input Validates whether it's an integer. If not it rebukes and exits. If it is, it loops through the collatz sequence until the result is 1 and then you win.

提交回复
热议问题