Python true false type

Booleans, True or False in Python

A boolean is a variable that is either True or False. We say the datatype of a variable can be booelan. In numeric context, it’s like a number that can either be 0 or 1. In electronics, it’s either high or low.

You can think of it like a light switch, its either on or off. Its based on the smallest unit in a computer, a bit. A bit is a value that is either 0 (False) or 1 (True). You can view a bit as synonym of boolean for now.

Introduction

A boolean values can have either a False or True value. In Python boolean builtins are capitalized, so True and False.

You do not need to explicitly define the data type to boolean.

You don’t need to say “I want to use a boolean” as you would need in C or Java. Instead Python knows the variable is a boolean based on the value you assign.

Compare the code below on boolean definition:

# Java
boolean fun = true;

# Python
fun = true

Boolean in Python

To define a boolean in Python you simply type:

That creates a boolean with variable name (a), and has the value False.
If you want to set it to on, you would type:

The value of a variable can be shown with the print function. If you use the Python shell you can just type the variable name:

You might think that that’s a boolean, but if you request the type you get int (number, integer):

Python requires you to call the bool() method to convert a number to a boolean.

Cast boolean

You can cast a value to a boolean using the function bool() . If you cast a variable, the data type is changed. In the example below it goes from data type int to boolean.

>>> x = 1
>>> b = bool(x)
>>> print(b)
True
>>> x = 0
>>> b = bool(x)
>>> print(b)
False
>>>

You can verify this by using the type() method call, which returns the datatype.

>>> x = 1
>>> type(x)
classint‘>
>>> x = bool(x)
>>> type(x)
classbool‘>
>>>

Boolean strings

Sometimes functions return a boolean value. If you define a string (text) you can call several methods on it, all which return a boolean value.

>>> s = «Hello World»
>>> s.isalnum()
False
>>> s.isalpha()
False
>>> s.isdigit()
False
>>> s.istitle()
True
>>> s.isupper()
False
>>> s.islower()
False
>>> s.isspace()
False
>>> s.endswith(«d»)
True
>>> s.startswith(«H»)
True
>>>

If you change the string value s , it will return different boolean values.

>>> s = «12345»
>>> s.isdigit()
True
>>> s.endswith(«d»)
False
>>>

Источник

Python Boolean

Summary: in this tutorial, you’ll learn about the Python boolean data type, falsy and truthy values.

Introduction to Python Boolean data type

In programming, you often want to check if a condition is true or not and perform some actions based on the result.

To represent true and false, Python provides you with the boolean data type. The boolean value has a technical name as bool .

The boolean data type has two values: True and False .

Note that the boolean values True and False start with the capital letters ( T ) and ( F ).

The following example defines two boolean variables:

is_active = True is_admin = FalseCode language: Python (python)

When you compare two numbers, Python returns the result as a boolean value. For example:

>>> 20 > 10 True >>> 20 < 10 FalseCode language: Python (python)

Also, comparing two strings results in a boolean value:

>>> 'a' < 'b' True >>> 'a' > 'b' FalseCode language: Python (python)

The bool() function

To find out if a value is True or False , you use the bool() function. For example:

>>> bool('Hi') True >>> bool('') False >>> bool(100) True >>> bool(0) FalseCode language: Python (python)

As you can see clearly from the output, some values evaluate to True and the others evaluate to False .

Falsy and Truthy values

When a value evaluates to True , it’s truthy. And if a value evaluates to False , it’s falsy.

The following are falsy values in Python:

  • The number zero ( 0 )
  • An empty string »
  • False
  • None
  • An empty list []
  • An empty tuple ()
  • An empty dictionary <>

The truthy values are the other values that aren’t falsy.

Note that you’ll learn more about the None , list , tuple , and dictionary in the upcoming tutorials.

Summary

  • Python boolean data type has two values: True and False .
  • Use the bool() function to test if a value is True or False .
  • The falsy values evaluate to False while the truthy values evaluate to True .
  • Falsy values are the number zero, an empty string, False, None, an empty list, an empty tuple, and an empty dictionary. Truthy values are the values that are not falsy.

Источник

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. ⭐️

Источник

Читайте также:  Call JavaScript function on page load.
Оцените статью