Candice Moore
Candice Moore

Reputation: 11

Automate the boring tasks - exercise - collatz function

Beginner question here.

I have just attempted an exercise from Automate the boring stuff. I've completed the question in the format suggested by first defining a function as below:

"Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1."

and then using that same function, meeting those minimal constraints, to write a programme that meets the following requirements:

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.

I've managed to generate a sequence of numbers ending with one, following the above rules, but my program prints each number in the sequence three times. Is anyone able to explain why this might be?

Thanks so much for your help

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

collatz(5)    
print('Enter a number')

entry = input()

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

Upvotes: 0

Views: 124

Answers (3)

user36339
user36339

Reputation: 273

You can try:

def collatz(number): if number == 0: return 'Try again with an integer other than 0' elif number == 1: return 1 elif number % 2 == 0: n = number // 2 print(n) elif number % 2 == 1: n = 3 * number + 1 print(n) while n != 1: n = collatz(n) return n return n

The last statement return n in line 15 is optional.

Upvotes: 0

AChampion
AChampion

Reputation: 30268

You are calling the function 3 times and you have a print call in the function.

Only call the function once and I would remove the print statements from the collatz method and just print in the calling loop, e.g.:

In []:
def collatz(number):
    if number % 2 == 0:
        return number//2
    return 3*number + 1

entry = int(input("Enter a number: "))
print(entry)

while entry != 1:
    entry = collatz(entry)
    print(entry)

Out[]:
Enter a number: 10
10
5
16
8
4
2
1

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

Your loop should look like this:

entry = input()
while entry != 1:
    entry = collatz(entry)

Upvotes: 2

Related Questions