0

I am a bit confused with if/else statement. Why the code always prints True while it should be False.

I have tried with different variables like i =10, i = 'a', i = 25. And it will be False if i=[]

This is my code:

i =1 if i: print True else: print False

user456
  • 29
  • 4
  • 3
    its false for 0. isn't it nice to be able to check if a number is non zero, or a string non empty, and so on? :) – Paritosh Singh Dec 29 '18 at 11:13
  • Why do you think it should be `False` on any of these examples? – glglgl Dec 29 '18 at 11:13
  • Because as far as I knew, If i: is equal to if i==1.Isn't it? – user456 Dec 29 '18 at 11:15
  • 1
    No, it isnt. Here's some [docs](https://docs.python.org/3/library/stdtypes.html#truth-value-testing). So (tl;dr its more close to `bool(i)` which translates to `i !=0` for ints. Different languages have different conventions, and you have to be careful assuming things. – Paritosh Singh Dec 29 '18 at 11:18

1 Answers1

-1

In your code you say if I: True. But your not comparing it to anything. You need a comparison operator. Like if i == 1 otherwise the if statement will just be true IF I has a value by default

Flightdoc5242
  • 199
  • 1
  • 2
  • 12
  • "Not comparing it to anything" is incorrect. In a line `if x:`, *x itself* is evaluated as a Truthy/Falsy value, and so is equivalent to `if bool(x) == True`. – Jongware Dec 29 '18 at 22:10