Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - if statement without a 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...