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
202 views
in Technique[技术] by (71.8m points)

python - "if", and "elif" chain versus a plain "if" chain

I was wondering, why is using elif necessary when you could just do this?

if True:
    ...
if False:
    ...
...
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You'd use elif when you want to ensure that only one branch is picked:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
elif spam == 'eggs':
    # won't do this.

Compare this with:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
if spam == 'eggs':
    # *and* do this.

With just if statements, the options are not exclusive.

This also applies when the if branch changes the program state such that the elif test might be true too:

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
elif foo == 'spam':
    # this is skipped, even if foo == 'spam' is now true
    foo = 'ham'

Here foo will be set to 'spam'.

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
if foo == 'spam':
    # this is executed when foo == 'bar' as well, as 
    # the previous if statement changed it to 'spam'.
    foo = 'ham'

Now foo is set to 'spam', then to 'ham'.

Technically speaking, elif is part of the (compound) if statement; Python picks the first test in a series of if / elif branches that tests as true, or the else branch (if present) if none are true. Using a separate if statement starts a new selection, independent of the previous if compound statement.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...