If statement without condition

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 does he say? what does "if x:" mean? usually there is always a condition after the if statement, but that doesn't. how can i figure it out? and what is he doing in this fuction?

+3


source to share


3 answers


You need to check if x is true or false (binary).

if x:

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

For example:

a = 10
if a:
    print a

      

Will print '10'

a = 'DaiMaria'
if a:
    print a

      

Will print 'DaiMaria'



a = 0.1
if a:
    print a

      

Fingerprints 0.1

a = 0
if a:
    print a

      

Doesn't print anything as it returns False.

a = None
if a:
    print a

      

Doesn't print anything because it returns False.

a = ''
if a:
    print a

      

Doesn't print anything because it returns False.

+2


source


The condition is whether x is a plausible value



+1


source


Your operator if

is equivalent to if bool(x): ...

where Python tries to first look for a method __nonzero__

to x

( __bool__

in Python 3), and if he can not find it, it returns True

the default if x

the same None

, False

has a method __len__

that returns a zero, is empty the display or numeric type with a value of 0.

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

      

0


source







All Articles