0

I am not getting any output from interpreter after I input a value.

Here's my code:

number = int(input("Enter the number to test:"))
count = 0
if number % 2 == 0:
        while number > 1:
            number /= 2
            count += 1
else:
    while number > 1:
        number = (3 * number) + 1
        count += 1

print("Iteration count: " + count)

Expected output is 15 for input = 11

Edit: The Collatz Conjecture (above) use the following algorithm: If n is even, divide it by 2, else multiply by 3 and add 1. Start over until you get 1.

Hiranya
  • 19
  • 6
  • 2
    Because `number` will always be greater than 1 when odd, and you entered an infinite loop – Federico klez Culloca Feb 24 '19 at 10:45
  • You need to move the even/odd test *inside* the loop. As it stands, look what happens if it's odd: It just keeps tripling it and adding 1 forever, since it will remain > 1`. Also, change `number /= 2` to `number //= 2`, otherwise it will be converted to floating point. – Tom Karzes Feb 24 '19 at 10:45
  • `number = (3 * number) + 1` will continue to increase the value, so `while number > 1:` will always be True. As Fedrico pointed out. – Torxed Feb 24 '19 at 10:45
  • Because `number = (3 * number) + 1` will go infinite.. `number` will never be less than one. So, while loops never end. – Ashwani Shakya Feb 24 '19 at 10:46
  • 1
    "If n is even, divide it by 2, else multiply by 3 and add 1. Start over until you get 1." - this is not what your code does. You should put the if statements into the loop. As of now, your algorithm doesn't have anything to do with the Collatz conjecture – ForceBru Feb 24 '19 at 10:50
  • Search SO for python + collatz - you can find working examples and compare them to what you got - yours is not quite right. – Patrick Artner Feb 24 '19 at 10:59
  • You might also want to read through [how-to-step-through-python-code-to-help-debug-issues](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues) or [How to debug small programs (#1)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) which will teach you about debugging - the best skill to learn as someone trying to code. – Patrick Artner Feb 24 '19 at 11:00

1 Answers1

3

You have created an infinite loop in your while statements. A good way you can check this yourself is to print number inside the while loop, and you will quickly see where you are going wrong.

I don't want to give away the solution as this sounds too much like homework - but you must ensure your while loop condition is met, or it will never exit.

JamoBox
  • 764
  • 9
  • 23
  • This only partially addresses the problems. The other problem, which I pointed out, is that `number` is being converted to floating point by the divide-by-two operator. The `/=` operator is incorrect. It needs to be `//=` in Python 3. It might work as floating point, but it clearly isn't desirable. – Tom Karzes Feb 24 '19 at 11:02