Last updated: Apr 9, 2024
Reading timeยท2 min

To take user input boolean values:
input() function to take input from the user.True or False.user_input = '' while True: user_input = input('Subscribe to newsletter? True / False: ') if user_input.capitalize() == 'True': print('The user typed in True') break elif user_input.capitalize() == 'False': print('The user typed in False') break else: print('Enter True or False') continue

We used a while loop to iterate until the
user enters a True or False value.
The input() function takes an optional prompt
argument and writes it to standard output without a trailing newline.
The function then reads the line from the input, converts it to a string and returns the result.
input() function is guaranteed to return a string even if the user enters a boolean value.Converting any non-empty string to a boolean returns True.
print(bool('a')) # ๐๏ธ True print(bool('False')) # ๐๏ธ True print(bool('')) # ๐๏ธ False

This is why we compare the user input value to the strings True and False
instead.
user_input = '' while True: user_input = input('Subscribe to newsletter? True / False: ') if user_input.capitalize() == 'True': print('The user typed in True') break elif user_input.capitalize() == 'False': print('The user typed in False') break else: print('Enter True or False') continue
The if statement checks if the user input value is equal to the string True.
If the condition is met, we print the value and break out of the while loop.
The break statement breaks out of the innermost enclosing for or while loop.
The str.capitalize() function returns a copy of the string with the first character capitalized and the rest lowercased.
print('true'.capitalize()) # ๐๏ธ 'True' print('FALSE'.capitalize()) # ๐๏ธ 'False'
The str.capitalize method makes sure the first letter of the input value is
uppercase and the rest are lowercase.
If the provided value is neither True nor False, we use the
continue statement to
prompt the user again.
The continue statement continues with the next iteration of the loop.
while loop, we use the continue statement when the input is invalid, e.g. in an except block or an if statement.If the input is valid, we use the break statement to exit out of the while
loop.
You can learn more about the related topics by checking out the following tutorials: