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)
Peilonrayz
44.4k7 gold badges80 silver badges157 bronze badges
asked Jun 20, 2019 at 7:12
\$\endgroup\$
1

1 Answer 1

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
answered Jun 20, 2019 at 14:54
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.