-2

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Abhishek AN
  • 648
  • 7
  • 24

3 Answers3

3

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")
Ashgabyte
  • 154
  • 1
  • 5
2

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.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
1

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.

sj95126
  • 6,520
  • 2
  • 15
  • 34
  • [benchmark](https://tio.run/##lY/LCsIwEEX3@YprQZJoFpYgiKA/UrqoNupA8yAdF/rztQ/34uzuPM5w0osfMdhDysNwy9GDyTtikE8x8zcJcY2t63FCJTCWrIqUHfMLvW@6rjAovGvp6dHT2xkEurrV1L3QHalrplRXqsmuwfmEcq@xxTei3OlamoWr/ufqH9xaiFvMmARAAYvIBvY4f@TRaXFU08RAztcjy0o9b6RMgZVc2xahh8Qaisf70lltZpoehg8) – Kelly Bundy Jul 18 '22 at 18:36