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("")
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("")
pass
else:
pass
Or just not have the else at all.
Or use print("")
as stated.
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("")
.
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:
else
blockelif
blockSo, 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.