9
votes
def f1(x,y):
      if x:    
          x = [1,2,3]
          x.append(4)
      else:
          x = 2
      return x + y

L1 = [1,2,3]
L2 = [55,66]
L3 = []
y = 3
print( f1(L3,y) )            # Line 1
print( L3 )                  # Line 2
print( f1(L1,L2) )           # Line 3
print( L1 )                  # Line 4

#I want to understand this expression, what is it saying? what does "if x:" means? usualy there is always a condition after the if statement, but this one doesn have one. how do I make sense of this? and what is it doing in this fuction?

3
That may be an if statement without a comparison but it definitely does have a condition. An if statement without a condition would look something like this: if : :-) - paxdiablo
you're right. I just used the wrong words, but I think you understood my question. can you give me an answer, please? - DiMaria

3 Answers

9
votes

It is to check whether x is true or false(binary).

if x:

returns true when the x value is not equal to 0(when x is a number) and it returns true if it has at least a character(when x is a string). It returns false if x is equal to '0' or '' or 'None'

For Eg:

a = 10
if a:
    print a

This prints '10'

a = 'DaiMaria'
if a:
    print a

This prints 'DaiMaria'

a = 0.1
if a:
    print a

Prints 0.1

a = 0
if a:
    print a

Prints nothing as it returned False.

a = None
if a:
    print a

Prints nothing as it returns False.

a = ''
if a:
    print a

Prints nothing as it returns False.

3
votes

The condition is whether or not x is a truthy value

0
votes

Your if statement is equivalent to if bool(x): ... where Python first tries to look for a __nonzero__ method on x (__bool__ in Python 3) and if it cannot find it returns True per default unless x is None, False, has a __len__ method that returns zero, is an empty mapping or a numeric type with value zero.

Some examples:

>>> class A(object):
...     pass
... 
>>> bool(A())
True
>>> class B(object):
...     def __nonzero__(self): return False
... 
>>> bool(B())
False
>>> class C(object):
...     def __len__(self): return 0
... 
>>> bool(C())
False
>>> class D(object):
...     def __len__(self): return 0
...     def __nonzero__(self): return True
... 
>>> bool(D())
True