w3resource

Python: Convert true to 1 and false to 0

Python Basic: Exercise-138 with Solution

Write a Python program to convert true to 1 and false to 0.

Sample Solution:

Python Code:

# Set the variable 'x' to the string 'true'.
x = 'true'

# Use the comparison 'x == 'true'' to check if 'x' is equal to the string 'true'. 
# The result of this comparison will be either True or False.

# Convert the result (True or False) into an integer (1 or 0) using the 'int()' function.
x = int(x == 'true')

# Print the value of 'x' after conversion. 
# If 'x' was 'true', it will be converted to 1 (True), and if 'x' was not 'true', it will be converted to 0 (False).
print(x)

# Set the variable 'x' to the string 'abcd'.
x = 'abcd'

# Repeat the same process: Use the comparison 'x == 'true'' to check if 'x' is equal to the string 'true'. 
# Convert the result (True or False) into an integer (1 or 0) using the 'int()' function.
x = int(x == 'true')

# Print the value of 'x' after conversion. 
# Since 'x' was not 'true', it will be converted to 0 (False).
print(x)

Sample Output:

1                                                                                                             
0  

Flowchart:

Flowchart: Convert true to 1 and false to 0.

Python Code Editor:

 

Previous: Write a Python program to extract single key-value pair of a dictionary in variables.
Next: Write a Python program to valid a IP address.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-138.php