r/PythonLearning • u/saikat_hossen • 7d ago
Python Boolean
I'm having some trouble understanding Python boolean logic, it’s so simple to let it be confusing. Can anyone explain it to me in their own language?
1
u/ninhaomah 7d ago
Show us the piece of code you don't understand.
1
u/saikat_hossen 7d ago
2
u/Lirianov 6d ago edited 6d ago
Booleans are very simple, its either True or False.
All of the below are considered False by Python:
NoneFalse0&0.0""(empty string)[],(),{}(empty list, set, or dict)Basically anything thats empty is False, all else are True.
looking at your code, you have:
age = input('Enter your age ')which is just taking a input from the user and saving it as a
stringthen:
has_NID = Truehere you're hardcoding the boolean
Truetohas_NIDthen your
ifstatement:if age == 18 and has_NID: print('You are not eligible for electing') else: print('You are eligible for electing')First thing I noticed is that your first
age == 18is incorrect for two reasons.First, you're comparing a
stringto aintwhich will always beFalse. Correct it by changing the value ofageto aint.if int(age) == 18 and has_NID:Next, you're checking if the user is 18 only, what if they are older? Someone who's 25 and has_NID will be told no. Correct it by checking if the person's age is equal or greater than 18.
if int(age) >= 18 and has_NID:Lastly, it seems you switched the two
ifstatement shouldprint('You are eligible for electing')and theelseshouldprint('You are not eligible for electing').BTW, is it supposed to be "electing" or "voting"?
Full correct code:
age = input("Enter your age ") has_NID = True if int(age) >= 18 and has_NID: print("You are eligible for voting") else: print("You are not eligible for voting")2
u/saikat_hossen 5d ago
Wow, this is so informative and detsiled. Thanks for going all the way through, I think I the hang of it. And it was originally for electing where the age was 25, then I thought of changing it to 18 as it wasn’t working.
2
2
u/NotLittleBoi 6d ago
Input returns a string. You need to cast it to an int by wrapping int() around your input
Also I’m pretty sure the different spacing of the print statements will get the compiler to yell at you too if one is done with tab spacing and the other is normal spacing
1
1
1

2
u/ConsiderationNo9044 7d ago
There are two boolean values: True and False. You usually compare them using two operators,
andandor. They mean exactly as they do in plain English.True
andTrue = True, because both values are True.True
andFalse = False, because one value is False, andandmeans both must be true.True
orFalse = True, because one value is True, andormeans one value must be True. You can probably guess the result of FalseorFalse.Any non-zero number is Truthy, meaning it represents True, while zero represents False. Any non-empty strings and collections are also Truthy.