1
\$\begingroup\$

I am a beginner in python. I found this problem in the book Automate the Boring Stuff with Python. How can I improve this program using latest version of python.

def generateCollatzSequence(number):
    print(str(number) + " ")

    while number != 1:
        if number % 2 == 0:
            number = number / 2
            print(str(number) + " ")

        elif number % 2 == 1:
            number = (3 * number) + 1
            print(str(number) + " ")

#print("Enter number: ")
inputNumber = int(input("Enter number: "))
generateCollatzSequence(inputNumber)
\$\endgroup\$
3
\$\begingroup\$
  • Your function is called generate but it doesn't return anything. Instead display would be a better name.
  • It would be better if you had two functions one to generate the values, one to display them.
  • Function names should be lower_snake_case to be idiomatic.
  • + " " is not needed, as print makes the value go to the next line anyway.
  • str(number) also isn't needed as print will do this automatically for you.

Thanks @Toby Speight:

  • You can move the print to be after both the if and the else.
def generate_collatz_sequence(number):
    output = [number]
    while number != 1:
        if number % 2 == 0:
            number = number / 2
        elif number % 2 == 1:
            number = (3 * number) + 1
        output.append(number)

def display_collatz_sequence(values):
    for number in values:
        print(number)

If you want this to still display values in real time, then you can make generate_collatz_sequence a generator function.

def generate_collatz_sequence(number):
    yield number
    while number != 1:
        if number % 2 == 0:
            number = number / 2
        elif number % 2 == 1:
            number = (3 * number) + 1
        yield number
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.