Collatz Sequence – getting a None at the end

Question:

Learning from “Automate The Boring Stuff” by Al Sweigart. At the end of Chapter 3, the Collatz Sequence is given as practice. The output seems correct, but the last row has a ‘None’ in it. In the code below, I am guessing that when p = 1, it gets out of the while loop, and then there is nothing to print, so it gives a None (?). Can someone point me in the right direction of why the None is added, and how to fix it?

See code right below and example results further down:

def collatz (p):
    while p != 1:
        if p % 2 ==0:
           p = (p//2)
           print(p)
        else:
           p = ((3*p) + 1)
           print(p) 

print ('Select a number between 1 and 10')
entry = float(input())
number = round(entry)
if number >10 or number <1:
   print('Your selection must between 1 and 10. Please try again')
else:       
   Program = collatz(number)
   print (Program)

**
Example results:
If I input number as 3, I get:

3
10
5
16
8
4
2
1
None
Asked By: Philomath

||

Answers:

As was already pointed out in the comments, your function returns None. I thought I’d take your function and make it a generator which you can iterate over and print the values that way. This has several advantages like making your code much more flexible and reusable:

def collatz (p):
    while p != 1:
        if p % 2 == 0:
           p = p / 2 # You don't need the double slash here because of the if before it
        else:
           p = (3*p) + 1

        yield p 

print('Select a number between 1 and 10')
number = int(input()) # You really want int here I think and leave out the rounding

if 1 <= number <= 10: # Slightly more pythonic
   for sequence_item in collatz(number):
       print(sequence_item)
else:
   print('Your selection must between 1 and 10. Please try again')

Feel free to ask anything or correct me on possibly wrong assumptions! 🙂

Answered By: whiterock