r/PythonLearning • • 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?

2 Upvotes

14 comments sorted by

View all comments

Show parent comments

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:

None False 0 & 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 string

then:

has_NID = True

here you're hardcoding the boolean True to has_NID

then your if statement:

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 print statement is not indented 4 spaces. Also, your age == 18 is incorrect for two reasons.

First, you're comparing a string to a int which will always be False. Correct it by changing the value of age to a int.

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 print statements around. The if statement should print('You are eligible for electing') and the else should print('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

u/Lirianov 5d ago

did you get it to work?

2

u/saikat_hossen 4d ago

Yeah, it works now thanks to you. 👍