1

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}')
asked Nov 19, 2021 at 15:40
5
  • 1
    Where you take input is before the loop, not inside it; so that only happens once. Commented Nov 19, 2021 at 15:41
  • 1
    You can put your input code inside the while loop. Commented Nov 19, 2021 at 15:41
  • 3
    if x < 0: will never be true, because you only go into the loop when x > 0 Commented Nov 19, 2021 at 15:42
  • I'm also not entirely sure that a while loop should be used, instead of a for Commented Nov 19, 2021 at 15:45
  • For loops are better if you want to do something a predetermined amount of times. While loops are better if you want to do something until a condition is met Commented Nov 19, 2021 at 15:47

1 Answer 1

1

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.

answered Nov 19, 2021 at 15:47
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the detailed answer, I will surely take another look at the loop and fix my mistakes. I was not entirely sure how the entire thing should look like however this has shined some light.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.