Making a collatz program automate the boring stuff

前端 未结 25 2259
一整个雨季
一整个雨季 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条回答
  •  -上瘾入骨i
    2020-12-08 11:47

    def collatz(num): 
        if num % 2: 
            return 3 * num + 1
        else:
            return num // 2
    
    while True:
        try:
        number = int(input('Enter a positive integer.'))  
        if number <= 0: 
            continue
        break
    except ValueError: 
        continue
    
    
    while number != 1:
        number = collatz(number)
        print(number)
    

提交回复
热议问题