Making a collatz program automate the boring stuff

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

    def collatz(number):
        if number % 2 == 0:
            return number // 2
        elif number % 2 == 1:
            return 3 * number + 1
    
    try:
        chosenInt = int(input('Enter an integer greater than 1: '))
    
        while chosenInt < 2:
            print("Sorry, your number must be greater than 1.")
            chosenInt = int(input('Enter an integer greater than 1: '))
    
        print(chosenInt)
    
        while chosenInt != 1:
            chosenInt = collatz(chosenInt)
            print(chosenInt)
    
    except ValueError:
        print('Sorry, you must enter an integer.')
    

提交回复
热议问题