if var == False

Python

Python Problem Overview


In python you can write an if statement as follows

var = True
if var:
    print 'I\'m here'

is there any way to do the opposite without the ==, eg

var = False
if !var:
    print 'learnt stuff'

Python Solutions


Solution 1 - Python

Use not

var = False
if not var:
    print 'learnt stuff'

Solution 2 - Python

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:

var = False
if var is False:
    print('learnt stuff')

This prevents potentially unwanted behaviour such as:

var = []  # or None
if not var:
    print('learnt stuff') # is printed what may or may not be wanted

But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

Solution 3 - Python

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

Solution 4 - Python

var = False
if not var: print 'learnt stuff'

Solution 5 - Python

I think what you are looking for is the 'not' operator?

if not var

Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhedg1View Question on Stackoverflow
Solution 1 - PythonTamil Selvan CView Answer on Stackoverflow
Solution 2 - PythoncolidyreView Answer on Stackoverflow
Solution 3 - Pythonstonesam92View Answer on Stackoverflow
Solution 4 - PythonjwodderView Answer on Stackoverflow
Solution 5 - PythonCambiumView Answer on Stackoverflow