0

Let's say I have some if statements:

thing = true
if thing:
    #something i will decide later
else:
    print ("well that thing is not true")

If I am just leaving something there for testing or want to have it there for structural purposes or maybe it just makes sense with the rest of the code (like an if statement for each letter, but "Z" is empty, and i might add it later).

In Python, I absolutely CANNOT leave an if statement empty. Why is that? Is it something to do with the indentations and the getting confused? Is it because there are no brackets, so then somehow it will get messed up? I don't understand why I this is disallowed. Please explain. Thanks!

pledab
  • 120
  • 1
  • 13

5 Answers5

7

you can leave if statement empty by using pass statement like below:

if thing:
    pass

pass statement does nothing but act as a placeholder.

Maninder Singh
  • 829
  • 1
  • 7
  • 13
2

That is because blank spaces means a great deal to python unlike other languages like C++ and java. Python uses blank spaces to structure code and define code blocks and scopes. If you want to keep it blank just write pass and python will not care about the if statement

Ezio
  • 2,837
  • 2
  • 29
  • 45
0

You need to have a pass keyword in your if block.

See this SO answer for why: https://stackoverflow.com/a/22612774/4227970

dongle man
  • 133
  • 1
  • 7
0

As it has already been mentioned you can use pass if you want to have an empty if statement or empty function body. However, you can also use negated if statement if you need to:

if not thing:
    print ("well that thing is not true")

It will make your code shorter.

Nurjan
  • 5,889
  • 5
  • 34
  • 54
0

Three characters shorter than Singh's:

if thing:
  0
Igor F.
  • 2,649
  • 2
  • 31
  • 39
  • we should not use `()` as an alternative to `pass`. you can compare the `disassembling` of your code when using `()` and using `pass` by using `dis` module. `from dis import dis` `dis(func_name)` – PradeepK May 31 '17 at 08:25
  • @PradeepK: OK, I modified my answer and even shortened it by one character :-) – Igor F. Jun 02 '17 at 01:34