-3

I'm new to Python and I having issues with my Collatz Sequence project in the Automate the Boring Stuff book. When I run my code it "prints" 2 of each number. I can't figure out why it is duplicating each number. Anyone have any ideas?

Here are the directions to the short project:

Write a function named collatz() that has one parameter named number. If the number is even, then collatz() should print number // 2 and return this value. If the number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.

def collatz(number):
if number % 2 == 0:
    print(number // 2)
    return number // 2
    
elif number % 2 == 1:
    print(3 * number + 1)
    return 3 * number + 1

print('Enter number: ')
try:
    x = int(input())
    while x != 1:
        collatz(x)
        x = collatz(x)        
except ValueError:
    print('Please use whole numbers only')

When I enter the number 3 I get this:

Enter number: 3 10 10 5 5 16 16 8 8 4 4 2 2 1 1

2 Answers2

0

Your issue is on the line:

    while x != 1:
        collatz(x)
        x = collatz(x)  

You are calling collatz twice, so it is printing each number twice.

Axe319
  • 4,255
  • 3
  • 15
  • 31
0

Here is the debugged version:

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    elif number % 2 == 1:
        print(3 * number + 1)
        return 3 * number + 1

print('Enter number: ')
try:
    x = int(input())
    while x != 1:
        x = collatz(x)
except ValueError:
    print('Please use whole numbers only')
Pedro
  • 330
  • 2
  • 12