Home > OS >  Conditional checking without if
Conditional checking without if

Time:07-19

I've been checking out how to do the below question without an if else condition, spent almost a day. Is it possible to do this without an if else?

Check if area is greater than or equal to 15, then print "big place!" or if area is greater than 10 but less than 15, then print "medium size, nice!" or print "pretty small".

I can think of a while and breaking it after first print for now.

CodePudding user response:

or construction with logical expression, either print it or assign to new variable:

area = 15
print("big place!" * (area >= 15) or "medium size, nice!" * (area > 10) or "pretty small")

CodePudding user response:

Sure you can. But why would you want to?

area >= 15 and print("big")
area < 15 and area >= 10 and print("medium")
area < 10 and print("small")

[It was unclear whether 10 precisely was medium or small.]

But this is horrible code. Why wouldn't you want to use an if statement.

CodePudding user response:

You can do something like this:

["pretty small", "medium size, nice!", "big place!"][(area >= 15)   (area > 10)]

which relies on the fact that True and False are evaluated as 1 and 0 in an arithmetic context.

But cryptic code is usually not the right approach.

  • Related