Search code examples
pythonloopsif-statementwhile-loopmultiplication

Multiply by 2 - Python


The input takes numbers until a negative number is entered, every number before that is multiplied by 2 and the result is printed and formatted to the 2nd digit after the comma. I've tried the following, however the loop just continues endlessly giving me only 1 result, how can I make it stop and multiply with the next input instead?

x = float(input())
while x > 0:
    result = x * 2
    if x < 0:
        print('Negative number!')
    print(f'Result: {result:.2f}')

Solution

  • There are many issues with your code. Here's the fixed version:

    while True:
        x = float(input("Input: "))
        if x < 0:
            print('Negative number!')
            break
        else:
            result = x * 2
            print(f'Result: {result:.2f}')
    
    
    

    "break" is needed to interrupt the while loop on the first bad result.