-2

I´d like to know if there´s a way to shorten an "if", that contains more than one command.

I know you can do it for single command if´s like:

if x > y:
   print("normal if")

and it becomes:

if x > y: print("shortened if")

But how could it be done in this case, for example?

if x > y:
   print("normal if")
   some_number *= 2
code-glider
  • 239
  • 2
  • 3
Mateus Buarque
  • 255
  • 1
  • 2
  • 9
  • 1
    why do you want to "shorten" it? What's the benefit? – UnholySheep Jan 20 '18 at 14:38
  • just out of curiosity. But i think it would be useful for a huge enough file that has thousands of these "if´s", to make it smaller (that´s just a feeling tho, i can´t say it for sure) – Mateus Buarque Jan 20 '18 at 14:40
  • If you really want to put it into a single line you can use semicolons, e.g.: `if x > y: print("normal if"); some_number *= 2` but I would really recommend against it. It just makes it harder to read (without any benefit I can think of) – UnholySheep Jan 20 '18 at 14:41
  • 2
    Python is all about readability and clarity. Why would you want to avoid that? – Martijn Pieters Jan 20 '18 at 14:42
  • @MartijnPieters i just wanted to know really, i don´t intend to use it in my codes. – Mateus Buarque Jan 20 '18 at 14:46
  • @MateusBuarque the case of "I have thousands of these ifs" is arguably exactly where you should *avoid* doing that. The indent makes it very readable, a single-line `if` is much harder to notice when looking through the code. – Zinki Jan 20 '18 at 14:46
  • Is it possible to post a bigger part of the code? – Elmex80s Jan 20 '18 at 15:04
  • Is the `print` part of the code absolutely necessary? – Elmex80s Jan 20 '18 at 15:06
  • @Elmex80s it was just an example. And, yes, sometimes you do need more than 1 line inside of an if. – Mateus Buarque Jan 20 '18 at 15:47

1 Answers1

4

You can shorten the command if you use a semicolon. See the behavior of a python semicolon

if x > y:
   print("normal if")
   some_number *= 2

Can be shortened to

if x > y: print("normal_if"); some_number *= 2

I am not saying that this is the right thing to do but it is possible. I recommend against it since it is harder to read.

costrouc
  • 3,045
  • 2
  • 19
  • 23