Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
elif vs. if
#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


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