Phedg1
Phedg1

Reputation: 1968

if var == False

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'

Upvotes: 85

Views: 239538

Answers (5)

colidyre
colidyre

Reputation: 4666

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.

Upvotes: 69

Tamil Selvan C
Tamil Selvan C

Reputation: 20209

Use not

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

Upvotes: 170

stonesam92
stonesam92

Reputation: 4457

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

Upvotes: 29

Cambium
Cambium

Reputation: 19392

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

Upvotes: 0

jwodder
jwodder

Reputation: 57480

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

Upvotes: 3

Related Questions