Lucy L - 1 year ago 48
Python Question

# Python loop freezing with no error

I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:

``````print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+'   Steps needed: '+count)
``````

It freezes up without showing an error message, and I have no clue why this happens.

1) You are invoking `range()` incorrectly.

Your code: `for n in range(max - min):` produces the range of numbers starting at `0` and ending at the value `max-min`. Rather, you want the range of numbers starting at `min` and ending at `max`.

Try this:

``````for n in range(min, max):
``````

2) You are performing floating-point division, but this program should use only integer division. Try this:

``````num = num // 2
``````

3) You are updating the `count` variable in the wrong loop context. Try indenting it one stop.

4) Your final line could be:

``````print('Number: '+str(n)+'   Steps needed: '+str(count))
``````

Program:

``````print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+'   Steps needed: '+str(count))
``````

Result:

``````Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5

Number: 3   Steps needed: 7
Number: 4   Steps needed: 2
Number: 5   Steps needed: 5
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download