automate the boring stuff with python chapter 3 practice project

Question:

please help me.

for the practice project in chapter 3 of ‘automate the boring stuff with python’, I made my own code. but it has errors I could not fix.

def collatz(number):

    if number == 1:
        print('the sequence is done')

    elif number % 2 == 0:
        print(number / 2)
        collatz(number / 2)

    else:
        print(number * 3 + 1)
        collatz(number * 3 + 1)

def begin():

    try:
        num = int(input("enter an integer: "))

    except ValueError:
        print("Please enter an integer greater than 1.")
        begin()

    if not num > 1:
        print("Please enter an integer greater than 1.")
        begin()

    collatz(num)

begin()

running it makes a loop error. I have tried to fix it but I just got stuck on it.

Asked By: HM Chu

||

Answers:

you’ve missed the base condition for your recrusive program.
You need to know recursion in order to understand how your code is behaving and functioning.
for now, the iterative version of your recursive program is:

def collatz(number):

    if number == 1:
        print("the sequence is done")

    elif number % 2 == 0:
        print(number / 2)
        collatz(number / 2)

    else:
        print(number * 3 + 1)
        collatz(number * 3 + 1)


def begin():

    while True:
        try:
            num = int(input("enter an integer: "))
            if not num > 1:
                print("Please enter an integer greater than 1.")
                continue
        except ValueError:
            print("Please enter a valid integer greater than 1.")
            continue
        collatz(num)
        break


if __name__ == "__main__":
    begin()
Answered By: Vishal Singh
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

try:
    user_input = int(input('Enter a number:n'))
    new_num = collatz(user_input)
    while new_num != 1:
        new_num = collatz(new_num)
except ValueError:
    print('Please enter an integer')

It says to print and return, so you don’t need to use recursion. Here’s how I did the program. I also used a while loop to repeat the process until a certain condition was met (until the value was 1).

Answered By: user17826218

Thank you for your solution to this problem. I am still unclear on what is meant by "print and return" vs just printing or returning? In fact I think I am just unclear on the real difference between printing and returning generally. Why is it crucial to do both of these for the recursive function to work properly?

Thank you,
J

Answered By: jkhl1103
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.