Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
elif vs. if
#1
Greetings:

Not a problem, just a query. Why should I use elif instead of multiple ifs? I wrote a simple program that used both methods and they both ran correctly.
Reply
#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
#3
response = input('Enter Yes No or Maybe')
if response == "Yes":
    print('Alright then')
elif response == "No":
    print('OK')
else
    print('Whenever you decide')

if response == "Yes":
    print('Alright then')
if response == "No":
    print('OK')
if response == "Maybe":
    print('Whatever you like')
These may look similar, but do have different behavior. In the first case, responds as you expect to Yes and No, and everything else defaults to the else which is Maybe. In the second case, it responds to Yes, No, and Maybe but will not respond to anything else, like 'Coconut'. The first example will treat Coconut as Maybe. So, it all depends on your particular switching needs.
Reply
#4
I haven't encountered the def function yet, so I'm not clear how that fits into my query, but thanks for the effort.
Reply
#5
On module level without a function:
upper = True
strip = True
text = " hEllO woRld "

if upper:
    # this is executed, because upper is True
    text = text.upper()
if strip:
    # This is a new if branch
    # strip is True
    # this is also executed
    text = text.strip()


print(text)
The other version:
upper = True
strip = True
text = " hEllO woRld "

if upper:
    # upper is True, this branch is executed
    text = text.upper()
elif strip:
    # strip is True, but the branch before was executed
    # so this one is not executed
    text = text.strip()

print(text)
With the first one you could use upper and strip together.
The second one is mutually exclusive. There you can use strip or upper but not both together.

This was just an example and has no much useful sense.


Functions are very important to organize your code, keeping the module namespace clean and they save a lot of repeating code.
On good example is a generic function, that asks a question and only the allowed answers return. If the answer was wrong, it repeats the question.


def ask(question, allowed_answers):
    """
    The function asks a question until an answer
    is equal on answer in allowed_answers.

    The function use casefold to compare the given answer.
    The original answer from allowed answers return
    """
    canonical_answers = [answer.casefold() for answer in allowed_answers]
    answers_str = "(" + ', '.join(allowed_answers) + ")"
    while True:
        answer = input(f"{question} {answers_str}: ").casefold()
        if answer in canonical_answers:
            index = canonical_answers.index(answer)
            return allowed_answers[index]
        else:
            print(answer, "is not in allowed")
And later somewhere else, you need to ask questions:
your_color = ask("Which color do you like?", ["Blue", "Red", "Yellow", "Green"])
your_pet = ask("Which pet do you like?", ["Cat", "Dog"])
Without functions, you have to repeat the code inside the
function over and over again and you have to do is right for each question.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

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