Making a collatz program automate the boring stuff

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

    def collatz(number):
        while number != 1:
            if number %2==0:
                number = number//2
                yield number
            elif number %2 ==1:
                number=number*3 +1
                yield number
    
    while True:
        try:
            for n in collatz(int(input('Enter number:'))):
                print(n)
            break
        except ValueError:
            print('Please enter an integer')
    

    The extra while True loop will help the program to continue functioning after the user inputs a non-integer.

提交回复
热议问题