How to Convert to Boolean in Python

Save

Programming languages use many different types of data, each of which has its own specific use. For example, a number can be stored in an integer data type, while a person's name can be stored in a string. A very important data type is the Boolean. A Boolean data type can be either true or false and it is often used to control program flow by deciding on the next course of action based on whether something evaluates as true or false. In Python, you can convert anything to a Boolean type.

  • Open the IDLE text editor that comes bundled with the Python programming language. A blank source code file appears in the main window of IDLE.

  • Declare a string type and assign it an arbitrary word, like this:

    x= 'Coffee'

  • Print out the value of the string like this:

    print(x)

  • Create a Boolean type by writing the following:

    Boolean = False

  • Convert the string 'str' to a Boolean using the Bool() function. You can then assign it to the variable Boolean like this:

    Bool = bool(x)

  • Print out the variable x again like this:

    print(x)

  • Press "F5" to execute the program. The first call to the print function prints out the word 'Coffee,' and is then converted to a Boolean. Any non-zero value that gets converted into a Boolean is considered to be equal to true. This means that when the string is printed out for a second time, it prints out 'True.' The program output looks like this:

    coffee

    True

Promoted By Zergnet

Comments

Resources

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!