+ 1

When to decide to set up a variable to True or False?

I'm trying to figure out why some variables are set up directly with a false booleans value. Does anyone have some concrete example to provide and explain the reason for those actions in a real situation? Thanks in advance

9th Jul 2022, 8:15 AM
Alex | Python Instructor & Solutionist Thinker
Alex | Python Instructor & Solutionist Thinker - avatar
3 Respostas
+ 9
Hi Alexandre NAROLLES / Solutionist Thinker Many things in the world can be categorized i either black or white, on or off, true or false etc. In programming tests are classical examples. For example if you want to test if a number is even or odd, or if a year is a leap year not, or if a list is empty or not. In these cases the return value from a test function can be a boolean value 0 or 1, or False or True. To use boolean values in programming are therefore very common.
9th Jul 2022, 8:51 AM
Per Bratthammar
Per Bratthammar - avatar
+ 6
Concrete example: It is a Boolean value, whether you have Pro subscription or not. It controls your access to certain content, and controls if advertisements are shown to you or not.
9th Jul 2022, 9:01 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Alexandre NAROLLES / Solutionist Thinker , here is code that demonstrates the use of boolean flags when checking the requirements of a password: 2 digits minimum 2 special characters minimum 7 characters length as minimum inp = input() state_lst = [False,False,False] # list is preset with False for all conditions if len([x for x in inp if x.isdigit()]) >= 2: # check for digits state_lst[0] = True if len([x for x in inp if x in '!@#$%&*']) >= 2: # check for special characters state_lst[1] = True if len(inp) >= 7: # check for total length state_lst[2] = True print('Strong') if all(state_lst) else print('Weak') # if all items in the list are True, it prints "Strong", otherwise it prints "Weak"
9th Jul 2022, 2:40 PM
Lothar
Lothar - avatar