Search code examples
pythonpython-3.xwhile-loopinfinite-loopdivision

Infinite dividing by 2


I'm just a beginner in python. Im trying to make a script which divides a number (user input) infinitly by 2. I mean if user inputs it should divide it like this: "40/2 20/2 10/2 5/2 2.5/2 ..." My Code looks like this

print ('please insert a number')
num = input()
num=float(num)
while(num<1000):
    print(num/2)

Output is just user input divided by 2, and then the result is looped for ever. What can I do next to make my code as I want?


Solution

  • You can construct an infinite loop via a condition which is always True, e.g. scalar True:

    num = float(input('Please insert a number:\n'))
    
    while True:
        num /= 2
        print(num)
    

    In practice, this isn't useful. You can, for example, easily insert a break statement so that your loop stops when you reach a lower bound. Here we end the loop when the float value is indistinguishable from 0.

    num = float(input('Please insert a number:\n'))
    
    while True:
        num /= 2
        print(num)
        if num == 0:
            break
    

    Example with initial input of 500:

    Please insert a number:
    500
    250.0
    125.0
    62.5
    ...
    3.06e-322
    1.53e-322
    8e-323
    4e-323
    2e-323
    1e-323
    5e-324
    0.0