True and false values in 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.

Источник

Truthy and Falsy Values in Python: A Detailed Introduction

Estefania Cassingena Navone

Estefania Cassingena Navone

Truthy and Falsy Values in Python: A Detailed Introduction

Welcome

In this article, you will learn:

  • What truthy and falsy values are.
  • What makes a value truthy or falsy.
  • How to use the bool() function to determine if a value is truthy or falsy.
  • How to make objects from user-defined classes truthy or falsy using the special method __bool __ .

Let’s begin! ✨

🔹 Truth Values vs. Truthy and Falsy Values

Let me introduce you to these concepts by comparing them with the values True and False that we typically work with.

Expressions with operands and operators evaluate to either True or False and they can be used in an if or while condition to determine if a code block should run.

In this example, everything is working as we expected because we used an expression with two operands and an operator 5 < 3 .

But what do you think will happen if we try to run this code?

Notice that now we don’t have a typical expression next to the if keyword, only a variable:

image-3

Surprisingly, the output is:

If we change the value of a to zero, like this:

I’m sure that you must be asking this right now: what made the code run successfully?

The variable a is not a typical expression. It doesn’t have operators and operands, so why did it evaluate to True or False depending on its value?

The answer lies on the concept of Truthy and Falsy values, which are not truth values themselves, but they evaluate to either True or False .

🔸Truthy and Falsy Values

In Python, individual values can evaluate to either True or False . They do not necessarily have to be part of a larger expression to evaluate to a truth value because they already have one that has been determined by the rules of the Python language.

  • Values that evaluate to False are considered Falsy .
  • Values that evaluate to True are considered Truthy .

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below (and, or, not).

🔹 Boolean Context

When we use a value as part of a larger expression, or as an if or while condition, we are using it in a boolean context.

You can think of a boolean context as a particular «part» of your code that requires a value to be either True or False to make sense.

For example, (see below) the condition after the if keyword or after the while keyword has to evaluate to either True or False :

image-1

💡 Tip: The value can be stored in a variable. We can write the name of the variable after the if or while keyword instead of the value itself. This will provide the same functionality.

Now that you know what truthy and falsy values are and how they work in a boolean context, let’s see some real examples of truthy and falsy values.

🔸 Falsy Values

Sequences and Collections:

  • Empty lists []
  • Empty tuples ()
  • Empty dictionaries <>
  • Empty sets set()
  • Empty strings «»
  • Empty ranges range(0)

Falsy values were the reason why there was no output in our initial example when the value of a was zero.

The value 0 is falsy, so the if condition will be False and the conditional will not run in this example:

>>> a = 0 >>> if a: print(a) # No Output 

🔹 Truthy Values

Truthy values include:

  • Non-empty sequences or collections (lists, tuples, strings, dictionaries, sets).
  • Numeric values that are not zero.
  • True

This is why the value of a was printed in our initial example because its value was 5 (a truthy value):

>>> a = 5 >>> if a: print(a) # Output 5

🔸 The Built-in bool() Function

You can check if a value is either truthy or falsy with the built-in bool() function.

According to the Python Documentation, this function:

Returns a Boolean value, i.e. one of True or False . x (the argument) is converted using the standard truth testing procedure.

image-2

You only need to pass the value as the argument, like this:

>>> bool(5) True >>> bool(0) False >>> bool([]) False >>> bool() True >>> bool(-5) True >>> bool(0.0) False >>> bool(None) False >>> bool(1) True >>> bool(range(0)) False >>> bool(set()) False >>> bool() True

💡 Tip: You can also pass a variable as the argument to test if its value is truthy or falsy.

🔹 Real Examples

One of the advantages of using truthy and falsy values is that they can help you make your code more concise and readable. Here we have two real examples.

Example:
We have this function print_even() that takes as an argument a list or tuple that contains numbers and only prints the values that are even. If the argument is empty, it prints a descriptive message:

def print_even(data): if len(data) > 0: for value in data: if value % 2 == 0: print(value) else: print("The argument cannot be empty")

We can make the condition much more concise with truthy and falsy values:

If the list is empty, data will evaluate to False . If it’s not empty, it will evaluate to True . We get the same functionality with more concise code.

This would be our final function:

def print_even(data): if data: for value in data: if value % 2 == 0: print(value) else: print("The argument cannot be empty")

Example:
We could also use truthy and falsy values to raise an exception (error) when the argument passed to a function is not valid.

>>> def print_even(data): if not data: raise ValueError("The argument data cannot be empty") for value in data: if value % 2 == 0: print(value)

In this case, by using not data as the condition of the if statement, we are getting the opposite truth value of data for the if condition.

Let’s analyze not data in more detail:

  • It will be a falsy value, so data will evaluate to False .
  • not data will be equivalent to not False , which is True .
  • The condition will be True .
  • The exception will be raised.
  • It will be a truthy value, so it will evaluate to True .
  • not data will be equivalent to not True , which is False .
  • The condition will be False .
  • The exception will not be raised.

🔸 Making Custom Objects Truthy and Falsy Values

If you are familiar with classes and Object-Oriented Programming, you can add a special method to your classes to make your objects act like truthy and falsy values.

__bool __()

With the special method __bool__() , you can set a «customized» condition that will determine when an object of your class will evaluate to True or False .

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object.

For example, if we have this very simple class:

>>> class Account: def __init__(self, balance): self.balance = balance

You can see that no special methods are defined, so all the objects that you create from this class will always evaluate to True :

>>> account1 = Account(500) >>> bool(account1) True >>> account2 = Account(0) >>> bool(account2) True

We can customize this behavior by adding the special method __bool__() :

>>> class Account: def __init__(self, balance): self.balance = balance def __bool__(self): return self.balance > 0

Now, if the account balance is greater than zero, the object will evaluate to True . Otherwise, if the account balance is zero, the object will evaluate to False .

>>> account1 = Account(500) >>> bool(account1) True >>> account2 = Account(0) >>> bool(account2) False

💡 Tip: If __bool__() is not defined in the class but the __len__() method is, the value returned by this method will determine if the object is truthy or falsy.

🔹 In Summary

  • Truthy values are values that evaluate to True in a boolean context.
  • Falsy values are values that evaluate to False in a boolean context.
  • Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None , and False .
  • Truthy values include non-empty sequences, numbers (except 0 in every numeric type), and basically every value that is not falsy.
  • They can be used to make your code more concise.

I really hope you liked my article and found it helpful. Now you can work with truthy and falsy values in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️

Источник

Booleans, True or False in Python

Boolean values are the two constant objects False and True.

They are used to represent truth values (other values can also be considered
false or true).

In numeric contexts (for example, when used as the argument to an
arithmetic operator), they behave like the integers 0 and 1, respectively.

The built-in function bool() can be used to cast any value to a Boolean,
if the value can be interpreted as a truth value

They are written as False and True, respectively.

Boolean Strings

A string in Python can be tested for truth value.

The return type will be in Boolean value (True or False)

Let’s make an example, by first create a new variable and give it a value.

 my_string = "Hello World" my_string.isalnum() #check if all char are numbers my_string.isalpha() #check if all char in the string are alphabetic my_string.isdigit() #test if string contains digits my_string.istitle() #test if string contains title words my_string.isupper() #test if string contains upper case my_string.islower() #test if string contains lower case my_string.isspace() #test if string contains spaces my_string.endswith('d') #test if string endswith a d my_string.startswith('H') #test if string startswith H To see what the return value (True or False) will be, simply print it out. my_string="Hello World" print my_string.isalnum() #False print my_string.isalpha() #False print my_string.isdigit() #False print my_string.istitle() #True print my_string.isupper() #False print my_string.islower() #False print my_string.isspace() #False print my_string.endswith('d') #True print my_string.startswith('H') #True 

Boolean and logical operators

Boolean values respond to logical operators and / or

Remember that the built-in type Boolean can hold only one of two possible
objects: True or False

Источник

Читайте также:  Скорость загрузки html wordpress
Оцените статью