Making a collatz program automate the boring stuff

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

    I had a hard time understanding the logic of this exercise. but I don't know what I did wrong to display the error if we have a negative number.

    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
    
    while True:
    try:
        entry = input('enter a positive number: ')
        while entry != 1:
            entry = collatz(int(entry))
    
        # if we have a negative number
        while entry < 1:
            break
    
    except ValueError:
        print('Error, enter valid number')
    

提交回复
热议问题