Check if true or false python

Python Booleans

Booleans represent one of two values: True or False .

Boolean Values

In programming you often need to know if an expression is True or False .

You can evaluate any expression in Python, and get one of two answers, True or False .

When you compare two values, the expression is evaluated and Python returns the Boolean answer:

Example

When you run a condition in an if statement, Python returns True or False :

Example

Print a message based on whether the condition is True or False :

if b > a:
print(«b is greater than a»)
else:
print(«b is not greater than a»)

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return,

Example

Evaluate a string and a number:

Example

Most Values are True

Almost any value is evaluated to True if it has some sort of content.

Any string is True , except empty strings.

Any number is True , except 0 .

Any list, tuple, set, and dictionary are True , except empty ones.

Example

The following will return True:

Some Values are False

In fact, there are not many values that evaluate to False , except empty values, such as () , [] , <> , «» , the number 0 , and the value None . And of course the value False evaluates to False .

Example

The following will return False:

One more value, or object in this case, evaluates to False , and that is if you have an object that is made from a class with a __len__ function that returns 0 or False :

Example

class myclass():
def __len__(self):
return 0

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

Example

Print the answer of a function:

def myFunction() :
return True

You can execute code based on the Boolean answer of a function:

Example

Print «YES!» if the function returns True, otherwise print «NO!»:

def myFunction() :
return True

if myFunction():
print(«YES!»)
else:
print(«NO!»)

Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:

Example

Check if an object is an integer or not:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Checking for True or False

The «bad» ways are not only frowned upon but also slower. Let’s use a simple test:

$ python -m timeit -s "variable=False" "if variable == True: pass"
10000000 loops, best of 5: 24.9 nsec per loop

$ python -m timeit -s "variable=False" "if variable is True: pass"
10000000 loops, best of 5: 17.4 nsec per loop

$ python -m timeit -s "variable=False" "if variable: pass"
20000000 loops, best of 5: 10.9 nsec per loop

Using is is around 60% slower than if variable (17.4/10.9≈1.596), but using == is 120% slower (24.9/10.9≈2.284)! It doesn’t matter if the variable is actually True or False — the differences in performance are similar (if the variable is True , all three scenarios will be slightly slower).

Similarly, we can check if a variable is not True using one of the following methods:

$ python -m timeit -s "variable=False" "if variable != True: pass"
10000000 loops, best of 5: 26 nsec per loop

$ python -m timeit -s "variable=False" "if variable is not True: pass"
10000000 loops, best of 5: 18.8 nsec per loop

$ python -m timeit -s "variable=False" "if not variable: pass"
20000000 loops, best of 5: 12.4 nsec per loop

if not variable wins. is not is 50% slower (18.8/12.4≈1.516) and != takes twice as long (26/12.4≈2.016).

The if variable and if not variable versions are faster to execute and faster to read. They are common idioms that you will often see in Python (or other programming languages).

About the «Writing Faster Python» series #

«Writing Faster Python» is a series of short articles discussing how to solve some common problems with different code structures. I run some benchmarks, discuss the difference between each code snippet, and finish with some personal recommendations.

Are those recommendations going to make your code much faster? Not really.
Is knowing those small differences going to make a slightly better Python programmer? Hopefully!

You can read more about some assumptions I made, the benchmarking setup, and answers to some common questions in the Introduction article. And you can find most of the code examples in this repository.

«truthy» and «falsy» #

Why do I keep putting «bad» in quotes? That’s because the «bad» way is not always bad (it’s only wrong when you want to compare boolean values, as pointed in PEP8). Sometimes, you intentionally have to use one of those other comparisons.

In Python (and many other languages), there is True , and there are truthy values. That is, values interpreted as True if you run bool(variable) . Similarly, there is False , and there are falsy values (values that return False from bool(variable) ). An empty list ( [] ), string ( «» ), dictionary ( <> ), None and 0 are all falsy but they are not strictly False .

Sometimes you need to distinguish between True / False and truthy/falsy values. If your code should behave in one way when you pass an empty list, and in another, when you pass False , you can’t use if not value .

Take a look at the following scenario:

def process_orders(orders=None): 
if not orders:
# There are no orders, return
return
else:
# Process orders
...

We have a function to process some orders. If there are no orders, we want to return without doing anything. Otherwise, we want to process existing orders.

We assume that if there are no orders, then orders parameter is set to None . But, if the orders is an empty list, we also return without any action! And maybe it’s possible to receive an empty list because someone is just updating the billing information of a past order? Or perhaps having an empty list means that there is a bug in the system. We should catch that bug before we fill up the database with empty orders! No matter what’s the reason for an empty list, the above code will ignore it. We can fix it by investigating the orders parameter more carefully:

def process_orders(orders=None): 
if orders is None:
# orders is None, return
return
elif orders == []:
# Process empty list of orders
...
elif len(orders) > 0:
# Process existing orders
...

The same applies to truthy values. If your code should work differently for True than for, let’s say, value 1 , we can’t use if variable . We should use == to compare the number ( if variable == 1 ) and is to compare to True ( if variable is True ). Sounds confusing? Let’s take a look at the difference between is and == .

is checks the identity, == checks the value #

The is operator compares the identity of objects. If two variables are identical, it means that they point to the same object (the same place in memory). They both have the same ID (that you can check with the id() function).

The == operator compares values. It checks if the value of one variable is equal to the value of some other variable.

Some objects in Python are unique, like None , True or False . Each time you assign a variable to True , it points to the same True object as other variables assigned to True . But each time you create a new list, Python creates a new object:

>>> a = True
>>> b = True
>>> a is b
True
# Variables that are identical are always also equal!
>>> a == b
True

# But
>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a is b
False # Those lists are two different objects
>>> a == b
True # Both lists are equal (contain the same elements)

It’s important to know the difference between is and == . If you think that they work the same, you might end up with weird bugs in your code:

a = 1
# This will print 'yes'
if a is 1:
print('yes')

b = 1000
# This won't!
if b is 1000:
print('yes')

In the above example, the first block of code will print «yes,» but the second won’t. That’s because Python performs some tiny optimizations and small integers share the same ID (they point to the same object). Each time you assign 1 to a new variable, it points to the same 1 object. But when you assign 1000 to a variable, it creates a new object. If we use b == 1000 , then everything will work as expected.

Conclusions #

  • To check if a variable is equal to True/False (and you don’t have to distinguish between True / False and truthy / falsy values), use if variable or if not variable . It’s the simplest and fastest way to do this.
  • If you want to check that a variable is explicitly True or False (and is not truthy/falsy), use is ( if variable is True ).
  • If you want to check if a variable is equal to 0 or if a list is empty, use if variable == 0 or if variable == [] .

Don’t miss new articles

No spam, unsubscribe with one click.

Источник

Check if true or false python

Last updated: Feb 20, 2023
Reading time · 3 min

banner

# Using booleans in an if statement in Python

Use the is operator to check for a boolean value in an if statement, e.g. if variable is True: .

The is operator will return True if the condition is met and False otherwise.

Copied!
variable = True # ✅ check if a variable has a boolean value of True if variable is True: # 👇️ this runs print('The boolean is True') # ------------------------------------------ # ✅ check if a variable is truthy if variable: # 👇️ this runs print('The variable stores a truthy value')

The first example checks if the variable stores a True boolean value.

You should use the is operator when you need to check if a variable stores a boolean value or None .

Use the equality operators (equals == and not equals != ) when you need to check if a value is equal to another value, e.g. ‘abc’ == ‘abc’ .

In short, use the is operator with built-in constants like True , False and None .

# Checking for False or a Falsy value

You can use the same approach when checking for False or a falsy value in an if statement.

Copied!
variable = False if variable is False: # 👇️ this runs print('The boolean is False') if not variable: # 👇️ this runs print('The variable stores a falsy value')

Note that checking for the boolean values True and False is very different than checking for a truthy or falsy value.

# Checking for a Truthy Value in an if statement

Here is how we would check for a truthy value in an if statement.

Copied!
variable = True if variable: # 👇️ this runs print('The variable stores a truthy value')

The falsy values in Python are:

  • constants defined to be falsy: None and False .
  • 0 (zero) of any numeric type
  • empty sequences and collections: «» (empty string), () (empty tuple), [] (empty list), <> (empty dictionary), set() (empty set), range(0) (empty range).
Copied!
if 'hello': print('this runs ✅') if ['a', 'b']: print('This runs ✅') if '': print('this does NOT run ⛔️') if 0: print('this does NOT run ⛔️')

if not X returns the negation of if X . So with if not X , we check if X stores a falsy value.

You will often have to use multiple conditions in a single if statement.

You can do that by using the boolean AND or boolean OR operators.

Copied!
if True and True: print('This runs ✅') if True and False: print('This does NOT run ⛔️') # -------------------------------------- if True or False: print('This runs ✅') if False or False: print('This does NOT run ⛔️')

The first two examples use the boolean AND operator and the second two examples use the boolean or operator.

When using the boolean and operator, the expressions on the left and right-hand sides have to be truthy for the if block to run.

In other words, both conditions have to be met for the if block to run.

Copied!
if True and True: print('This runs ✅') if True and False: print('This does NOT run ⛔️')

When using the boolean or operator, either of the conditions has to be met for the if block to run.

Copied!
if True or False: print('This runs ✅') if False or False: print('This does NOT run ⛔️')

If the expression on the left or right-hand side evaluates to a truthy value, the if block runs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Online html template free
Оцените статью