Python if boolean true false

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.

Источник

Python if boolean true false

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

using booleans in if statement

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

checking for false or 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')

checking for truthy value in if statement

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.

Источник

Python Boolean and Conditional Programming: if.. else

Besides numbers and strings, Python has several other types of data. One of them is the Boolean data type. Booleans are extremely simple: they are either true or false. Booleans, in combination with Boolean operators, make it possible to create conditional programs: programs that decide to do different things, based on certain conditions.

The Boolean data type was named after George Boole, the man that defined an algebraic system of logic in the mid 19th century.

What is a Boolean?

Let’s start with a definition:

Boolean A boolean is the simplest data type; it’s either True or False .

In computer science, booleans are used a lot. This has to do with how computers work internally. Many operations inside a computer come down to a simple “true or false.” It’s important to note, that in Python a Boolean value starts with an upper-case letter: True or False . This is in contrast to most other programming languages, where lower-case is the norm.

In Python, we use booleans in combination with conditional statements to control the flow of a program:

>>> door_is_locked = True >>> if door_is_locked: . print("Mum, open the door!") . Mum, open the door! >>>_

Here’s an interactive version of the same code that you can experiment with:

First, we define a variable called door_is_locked and set it to True . Next, you’ll find an if-statement. This is a so-called conditional statement. It is followed by an expression that can evaluate to either True or False . If the expression evaluates to True , the block of code that follows is executed. If it evaluates to False , it is skipped. Go ahead and change door_is_locked to False to see what happens.

An if can be followed by an optional else block. This block is executed only when the expression evaluates to False . This way, you can run code for both options. Let’s try this:

>>> door_is_locked = False >>> if door_is_locked: . print("Mum, open the door!") . else: . print("Let's go inside") . Let's go inside >>>_

Thanks to our else-block, we can now print an alternative text if door_is_locked is False . As an exercise, try to modify the interactive code example above to get the same result.

Python operators

The ability to use conditions is what makes computers tick; they make your software smart and allow it to change its behavior based on external input. We’ve used True directly so far, but more expressions evaluate to either True or False . These expressions often include a so-called operator.

There are multiple types of operators, and for now, we’ll only look at these:

Comparison operators

Let’s look at comparison operators first. You can play around with them in the REPL:

>>> 2 > 1 True >>> 2 < 1 False >>> 2 < 3 < 4 < 5 < 6 True >>> 2 < 3 >2 True >>> 3 >> 3 >= 2 True >>> 2 == 2 True >>> 4 != 5 True >>> 'a' == 'a' True >>> 'a' > 'b' False

This is what all the comparison operators are called:

Operator Meaning
> greater than
smaller than
>= greater than or equal to
smaller than or equal to
== is equal
!= is not equal

Python’s boolean operators

As can be seen in the examples, these operators work on strings too. Strings are compared in the order of the alphabet, with these added rules:

You’re probably wondering what the logic is behind these rules. Internally, each character has a number in a table. The position in this table determines the order. It’s as simple as that. See Unicode on Wikipedia to learn more about it if you’re interested.

Logical operators

Next up: logical operators. These operators only work on booleans and are used to implement logic. The following table lists and describes them:

Operator What is does Examples
and True if both statements are true True and False == False
False and False == False
True and True == True
or True if one of the statements is true True or False == True
True or True == True
False or False == False
not Negates the statement that follows not True == False
not False == True

Python logical operators

Here are some examples in the REPL to help you play around with these:

>>> not True False >>> not False True >>> True and True True >>> True and False False

Comparing different types in Python

When you try to compare different types, you’ll often get an error. Let’s say you want to compare an integer with a string:

This is how Python tells you it can’t compare integers to strings. But there are types that can mix and match. I would recommend against it because it makes your code hard to understand, but for sake of demonstration, let’s compare a boolean and an int:

>>> True == 1 True >>> False == 0 True >>> True + True 2 >>> False + False 0 >>> False + True 1 >>> True + 3 4 >>>

As can be seen, True has a value of 1, and False has a value of 0. This has to do with the internal representation of booleans in Python: they are a special kind of number in Python.

Get certified with our courses

Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Python Fundamentals II: Modules, Packages, Virtual Environments (2023)

NumPy Course: The Hands-on Introduction To NumPy (2023)

Learn more

This article is part of my Python tutorial. You can head over to the start of the tutorial here. You can navigate this tutorial using the buttons at the top and bottom of the articles. To get an overview of all articles in the tutorial, please use the fold-out menu at the top.

If you liked this article, you might also like to read the following articles:

Leave a Comment Cancel reply

You must be logged in to post a comment.

You are browsing the free Python tutorial. Make sure to check out my full Python courses as well.

Subscribe to my newsletter for Python news, tips, and tricks!

Источник

Читайте также:  Php форма имя телефона
Оцените статью