82

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'
0

5 Answers 5

160

Use not

var = False
if not var:
    print 'learnt stuff'
3
  • 14
    How would you differentiate between False and None?
    – AlxVallejo
    May 24, 2018 at 17:42
  • 4
    @AlxVallejo you made a good point here! That was worth an answer: stackoverflow.com/a/50978588/2648551 Thx for that suggestion.
    – colidyre
    Jul 11, 2018 at 11:12
  • 1
    lol was searching for it land on stakcoverflow , python is quite funny , i not understand why people love it so much.
    – user889030
    Oct 12, 2021 at 15:47
69

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.

1
  • 1
    I like this better because "explicit is better than implicit" Jun 29, 2022 at 12:23
29

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

3
var = False
if not var: print 'learnt stuff'
3
  • 2
    Why do all of these answers have the same example code, even though the original question didn't actually put the if and the print on the same line?
    – Blender
    May 13, 2013 at 1:02
  • @Blender: The first revision of the question messed up the formatting so that each code snippet appeared on a single line.
    – jwodder
    May 13, 2013 at 1:04
  • @Blender: when I look at the revision history, I see the "original" (hard to tell inside the grace period) code as being a one-liner due to misformatting.
    – DSM
    May 13, 2013 at 1:05
0

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

1
  • 8
    That site has bad documentation.
    – Blender
    May 13, 2013 at 1:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.