Kodeclik Blog

ABOUT

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

PROGRAMS

Computer Science Camps

Online CS Classes

Math Camps

Online Math Classes

Self Learning CS Courses

Coding Contest

POPULAR CLASSES

Scratch Coding

Minecraft Coding

TinkerCAD

Roblox Studio

Python for Kids

Javascript for Kids

Pre-Algebra

Geometry for Kids

Copyright @ Kodeclik 2024. All rights reserved.

Note that a boolean value is either True or False in Python and you might sometimes find a need to convert a boolean to a string. For instance consider the following function:

is_divisor() checks if the input x is a divisor of input y and returns a boolean - True or False as appropriate.

Let us suppose we wish to create a function that creates a pretty printed version of this information:

explain_if_divisor() prints out a string summarizes the input in the form of a question. Note that this question contains both string and numeric parts and we have used the str() function to typecast our integer inputs into strings before they are concatenated into the final message. The output of the above program is:

Now let us call the is_divisor() function and return the answer along with the question. But is_divisor() returns a boolean. How do we massage it into a string? Simple! Same as what we have done above - use the versatile str() function! Here is how that would work:

The output of the above program will be:

as intended.

In summary, there are many situations like the above where you will need to convert a boolean to a string in Python. The best solution is to simply use the str() function as done here.

If you liked this blogpost, learn how to do the reverse, i.e., how to convert a string in Python to a boolean!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

```
def is_divisor(x,y):
if (y % x == 0):
return(True)
else:
return(False)
```

```
def explain_if_divisor(x,y):
print("Is " + str(x) + " a divisor of " + str(y) + "? ")
explain_if_divisor(3,48)
```

`Is 3 a divisor of 48?`

```
def explain_if_divisor(x,y):
print("Is " + str(x) + " a divisor of " + str(y) + "? "
+ str(is_divisor(x,y)))
explain_if_divisor(3,48)
explain_if_divisor(3,47)
```

```
Is 3 a divisor of 48? True
Is 3 a divisor of 47? False
```