Links to: Variables & strings // Collections // Python editor // Loops // Working with text files // Exercises
Note: Python uses intendation! Each : is followed by a hard return + 4 spaces (or a tab). If you forget to use them, you’ll get a Syntax error.
Elements to remix a song: if, in, elif, else
# Prince, Purple Rain (using a hashtag = making a comment) verse = "I never meant to cause you any sorrow."
Transform string in list of words
words = verse.split()
word = 'never' if word in words: print(word + " is in the song.")
Exercise 1: Capitalize the word
print(word in words)
Because the word is in the verse, Python returns
True. Let’s do the same thing for a word that we know is not in the verse.
print("Prince" in words)
Back to our
if statement. If the expression after
if evaluates to
True, our program will go on to the next line and print
word + " is in the song"
if word in words: print("Yes!") if "Prince" in words: print("Yes!")
Notice that the last print statement is not executed. That is because the word Prince is not in the verse, and thus the part after
if did not evaluate to
Exercise 2: If the word is in the verse, double the word
If, in, else
We can use another statement besides
else. The part after
else will be evaluated if the
if statement evaluated to
False. In English: if the word is not in the verse, print that is is not.
word = 'Prince' if word in words: print(word + " is in the song.") else: print(word + " is NOT in the song.")
If, in, elif, else
Sometimes we have various conditions that should all evaluate to something different. For that Python provides the
elif statement. We use it similar to
else. Note however that you can only use
elif after an
if-elif-else combination, a very common way to implement ‘decision trees’ in Python.
word = "purple rain" if "a" in word: print(word + " contains the letter a") elif "p" in word: print(word + " contains the letter p") elif "d" in word: print(word + " contains the letter d") elif "n" in word: print(word + " contains the letter n") else: print("What a weird word!")
if statement will be evaluated. Only if that statement turns out to be
False the computer will proceed to evaluate the
elif statement. If the elif statement in turn would prove to be
False, the machine will proceed and execute the lines of code associated with the
else statement. You can think of this coding structure as a decision tree! Remember: if somewhere along the tree, your machine comes across a logical expression which is true, it won’t bother anymore to evaluate the remaining options!
Exercise 3: If a word is part of the verse, double the word three times, add it to the list and print the list as a string
What you’ve learned