Home > Back-end >  Can you have an else statement print something and break from a loop with one line?
Can you have an else statement print something and break from a loop with one line?

Time:11-12

So let's say I have something like this:

while True:
  if x == x: print("x is equal to itself!")
  else:
    print("something's not right")
    break

Is there a way to condense that else statement into a single line similar to the if statement?

CodePudding user response:

This will work for you:

while True:
  if x == x: print("x is equal to itself!")
  else: print("something's not right"); break

Also if x ALWAYS equals x the "Else" statement will never be used.

CodePudding user response:

To build on the other answers, here is my suggestion:

while True:
    if x == x: print('x is equal to itself!')
    else: print('x is nan!'); break;

Because in most programming languages, including python and js, NaN != NaN.

  • Related