Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
elif vs. if
#2
It depends what you want to do.
Here we have two independent if-blocks:
def foo(text, upper, strip):
    if upper:
        text = text.upper()
    if strip:
        text = text.strip()
    return text


foo('   Hello World   ', True, True)
But writing this with elif gives different results.
def foo(text, upper, strip):
    if upper:
        text = text.upper()
    elif strip:
        text = text.strip()
    return text


foo('   Hello World   ', True, True)
In this case upper is also True and the code-block is executed.
The second block after elif is not executed, because the first condition was true.
So only one if/elif/else-block is executed.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
elif vs. if - by mortarm - Feb-10-2020, 03:32 PM
RE: elif vs. if - by DeaD_EyE - Feb-10-2020, 03:46 PM
RE: elif vs. if - by jefsummers - Feb-10-2020, 09:07 PM
RE: elif vs. if - by mortarm - Feb-18-2020, 04:30 PM
RE: elif vs. if - by DeaD_EyE - Feb-18-2020, 06:31 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020