Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

running the collatz sequence code from automate the boring stuff with python

I am new to programming, while studying, I came across this practice project which is to write a program to run the collatz sequence from any number until it reaches 1, the code works but it prints each output twice.

`def collatz():
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    else:
        print(number * 3 + 1)
        return number * 3 + 1
number = 5
print("hi pick a number")
while number != 1:
    try:
        number = int(input())
        while number != 1:
            collatz()
            number = collatz()
    except ValueError:
        print("you should pick a number!")`

hi pick a number
16
8
8
4
4
2
2
1
1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your code you call twice collatz() so it print twice

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading