Quantcast
Viewing latest article 2
Browse Latest Browse All 4

Answer by 200_success for Python - The Collatz Sequence

Prompt

The most obvious bad practice here is the use of a global variable. Instead of setting num as a side-effect, your function should return the result.

getNum() is not such a good name for the function. PEP 8, the official style guide for Python, says that function names should be lower_case_with_underscores. Furthermore, "get" implies that the function is retrieving a piece of data that is already stored somewhere, which is not the case here. Finally, "Num" should be more specific.

The use of recursion is not appropriate. If you want a loop, write a loop.

def ask_integer():"""    Return an integer entered by the user (repeatedly prompting if    the input is not a valid integer)."""    while True:        try:            return int(input("> "))        except ValueError:            print("Please enter an integer")num = ask_integer()

collatz function

Strictly speaking, you didn't follow the instructions. Your solution isn't wrong or bad — you just didn't implement the collatz function according to the specification that was given, which says that you should print and return one single number.

def collatz(num):"""    Given a number, print and return its successor in the Collatz sequence."""    next = num // 2 if num % 2 == 0 else 3 * num + 1    print(next)    return nextnum = ask_integer()while num > 1:    num = collatz(num)

Viewing latest article 2
Browse Latest Browse All 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>