0

I have to print something on the screen if some condition is true but if the condition is wrong i need python to print nothing, how do i do that? I used the below code but is there any other way to do the same?

else:
     print("")
  • have you tried print() ? or how about ignoring the print statement via an if statement ? – Jawad Dec 31 '19 at 21:06
  • Why do you need another way? – jonrsharpe Dec 31 '19 at 21:06
  • why do you need python to print nothing? – SuperStew Dec 31 '19 at 21:08
  • @Jawad i did not get what you said in the latter, how via if statements? –  Dec 31 '19 at 21:08
  • or do you mean literally `print('nothing')` – SuperStew Dec 31 '19 at 21:08
  • @jonrsharpe & SuperStew because i need it to print something if the condition is true but i want it to print nothing when the condition is false. but i have to use the else condition every time we use if, right? –  Dec 31 '19 at 21:10
  • 1
    No, you don't have to. If you don't want to do anything in the `else` block, you don't have to include it at all (or you can just `pass` in it). – jonrsharpe Dec 31 '19 at 21:10
  • @TheAmayJain so just don't have an `else` ? – SuperStew Dec 31 '19 at 21:12
  • You presumably do not want Python to "print nothing" but rather you want Python "to not print". So simply don't execute print() at all in that case. If you actually have to execute code in that scenario, which is unlikely, then use `pass`. – jarmod Dec 31 '19 at 21:16

3 Answers3

3
  1. For else, you could use use pass
else:
   pass
  1. Or just not have the else at all.

  2. Or use print("") as stated.

Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35
0

Printint an empty string:

In Python 2.x, you can do:

print

In Python 3.x, you must do:

print()

Note that print() also works on Python 2.x, and so it is my recommendation that you go with this. It is functionally similar to print("").

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
0

because i need it to print something if the condition is true but i want it to print nothing when the condition is false. but i have to use the else condition every time we use if, right? –

No. That's not correct!

An if block in Python can be followed by either of the following:

  1. else block
  2. elif block
  3. Or non-conditional block or may be a different conditional block

So, an else block isn't necessary in python after every if block. You can skip that like below:

if x > 3:
    print("it is > 3")
print("Out of if block")

Just for your information: If you need to know how to have a print call which doesn't dp anything. In Python 2.x, you can do:

print

And in Python 3.x,

print()

It's better not to have such a call. You can also use pass in Python.

Python has the syntactical requirement that code blocks (after if, except, def, class etc.) cannot be empty. Therefore, if nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError.

abhiarora
  • 9,743
  • 5
  • 32
  • 57