Francisca
Francisca

Reputation: 1

How to use conditionals without relational operators

# x = 1
# x = 0

if x:
    print(f'x = {x}, and therefore it\'s truthy')
else:
    print(f"x = {x}, and therefore it's falsey")

Hi everyone, I am a little confused with this exercise. The code doesn't have any explanation as when the system should print truthy or falsey yet it knows when to print it. Why is that?

Upvotes: 0

Views: 120

Answers (4)

the funny part is if you use

x = 0.00000000000001

it will also consider as true. cause it is not actually equal to zero. in math we consider this as zero for easy calculation. but computer dont do this cause this can create big problem in calculation if we consider a big picture. Example:

y = x ** x
print(y)

so if we consider x as zero, y will be also zero. but its not. i hope you enjoyed to learn why 0.000000000001 is not equal to zero in computer.Thanks.

Upvotes: -1

quamrana
quamrana

Reputation: 39354

Its all in the if x: line.

To execute this line, I like to think that python translates it to:

if bool(x):

because bool() will only ever return True or False, then the first option is only ever taken when the result is True.

See this answer for details of a comprehensive list of values which are considered Falsey.

Upvotes: 0

Peterrabbit
Peterrabbit

Reputation: 2247

I think it's just a way to show that 0 is interpreted as False in a boolean expression like a comparison or an if etc, and 1 (or any other non-zero number) is interpreted as True.

Edit: and like said in some comments, the fact that a value is "truthy" doesn't mean that is strictly equal to True for example:

print(1 == True) # True
print(0 == False) # True
print(2 == True) # False
print(not not 2) # True
print(not 0) # True
print(not not 0) # False
print(0 and True) # False
print(2 and False) # False
print(2 and True) # True
print(0 or 2) # True
# etc ...

Upvotes: 2

Adon Bilivit
Adon Bilivit

Reputation: 26935

If x is an int and has a value of zero it is equal to False and therefore falsey. If x is an int and has a value of 1 it is equal to True and is therefore truthy. However, if x is an int and is neither 0 nor 1 it is truthy but not equal to True. Therefore, when x is of type int, if x: can be interpreted as 'if x is non-zero'

Upvotes: 0

Related Questions