What we’re doing: More Python, specifically the basics conditionals, loops, lists, and iteration.
Why we’re doing it: To learn more about how to think algorithmically and break problems we’re trying to solve into small steps that a computer can help with.
Preparation
Log on to a MathLAN computer and click on the Applications button in bottom left corner. Go to Development and then the program called IDLE 3. This will open a window that looks like a terminal window but running Python instead of a file directory. This is called the Shell screen. In it, you interact directly with Python.
Conditionals
Remember how we set variables in Twine that triggered different outputs in the next passage? That process of checking on something and varying the output based on the results of that check is called a conditional, and it is one of the core elements of computational algorithms.
The basic process of a conditional can be summarized like this:
if <something is true>:
<do something>
<do another thing>
This is called an if statement. What if we want to do something else if that “something” isn’t true? Python incorporates this alternative behavior with the else statement, which must follow an if:
if <something is true>:
<do something>
<do another thing>
else:
<do something else>
<do another different thing>
Some of our decisions may even involve a sequence of tests. Rather than following an else with another if, we can elide these together with elif:
if <something is true>:
<do something>
<do another thing>
elif <something else is true>:
<do something else>
<do another different thing>
else:
<do this thing>
<do this other thing>
It turns out we can add as many different tests with elif as we need. Now, let’s put them into practice.
What’s your favorite color?: Using if/else
Let’s see if we can make our graduation() function a little smarter-looking.
Remember that a run of our basic program looked something like this:
What year will you graduate? 2020
Congratulations! You have only 1 more year to go!
But what if you had more than one year? Or what if you had already graduated? Or what if you were graduating this spring, and had less than a year? We can anticipate that and build different answers based on the input.
Open a new file and start the following script:
def graduate2():
year = input(“What year will you graduate? “)
toGo = int(year) -2019
Now, instead of having just one answer to print based on that calculation, you can use if/elif/else to build multiple options by using a relational operator to evaluate the answer that you get. Specifically, we’re going to evaluate whether the person is graduating in one year, more than one year, this year, or has already graduated.
Enter the following as a continuation of your function:
if toGo == 1:
print(“Congratulations! You only have 1 year to go!”)
elif toGo == 0:
print(“Congratulations! You only have a few weeks to go!”)
elif toGo < 0:
print(“Hold on, did you already graduate?”)
else:
print(“Hang in there! You only have “ + str(toGo) + “ more years to go!”)
Save the file, run the module, and call the function, fixing any errors.
This example uses relational operators. Python has several of these, which should sound sort of familiar from math class:
Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Helpfully, these operators also work for strings, which you will now test out.
Write a function called favorite that asks the user to enter a color. If the color entered happens to be your favorite color, print a message to that effect. Otherwise, do not print any response.
Check your program. You’ll need to run it at least twice entering colors that test both outcomes.
Add one statement to your function that will cause it to print Goodbye! just before it ends, regardless of the color entered.
Finally, modify favorite so that it prints one message if the user enters your favorite color, and a different message if not. In addition, your program should print a final message for every user, regardless of what they entered.
While
What if you want your user to be able to make multiple guesses until they get it right? For that, we can use a while loop. A loop is a general term for repeating an operation.
Start building the following script in your file. You don’t have to type the comments, but they are there to explain what each part is doing:
def guessFavorite():
rightGuess = 0 ##set an opening condition that you will be able to change once the user gets the right answer
while rightGuess == 0: ##start the while loop
guess = input(“What is your favorite color? “)
if guess == “purple”:
print (“That’s my favorite color too!”)
rightGuess = rightGuess + 1 ##(this changes the counter and therefore the condition in which the loop will run)
else:
print(“Oh. I guess we’re not soul mates after all.”)
print(“Goodbye!”)
Things to note carefully:
The indentation: the if/else has to be indented under the while loop. This is called nesting. It is vital to tell Python the order in which to do things.
The input statement comes within the while loop: otherwise, if the user guesses wrong, when the program loops back around, it won’t prompt the user to enter another answer, and it will just keep printing the else statement. Try that out if you’re brave. (You can always close the Shell to make it stop.) This is called an infinite loop. You should try to avoid it. But it’s not a big deal in short programs like this, especially when you have an output that allows you to see when it is happening.
What if you wanted to give the user only a certain number of guesses? You can set multiple conditions at once:
def threeGuesses():
favorite = "purple"
guess = input("What is your favorite color? ")
guessNumber = 0
while guess != favorite and guessNumber <2:
guess = input("Oh. That's not my favorite color. Do you have another one?")
guessNumber = guessNumber + 1
if guessNumber == 2 and guess != favorite:
print("I guess we'll never be soul mates.")
else:
print("That's my favorite color, too!")
Save, run, and call this function, fixing any errors until it does what you want it to do.
Multiple spellings: using lists
So now you can find out if someone else’s favorite color is purple. But what if they type Purple? Or hit the caps lock and it comes out PURPLE?
You can ask Python to check different spellings if you tell them exactly what they are. To do that, we are going to use a new data type called a list. You create a list using square brackets and commas in between each list item:
favoriteList = [“purple”,”Purple”,”PURPLE”]
Now, write your function again, using a list:
def threeGuessesList():
favoriteList = [“purple”,”Purple”,”PURPLE”]
guess = input("What is your favorite color? ")
guessNumber = 0
while guess not in favoriteList and guessNumber <2:
guess = input("Oh. That's not my favorite color. Do you have another one?")
guessNumber = guessNumber + 1
if guessNumber == 2 and guess not in favoriteList:
print("I guess we'll never be soul mates.")
else:
print("That's my favorite color, too!")
For this problem, we used not in, but the more typical way is just to check if something is in, using this syntax:
list = [1, 2, 3,]
if 1 in list:
print(“yes”)
You can also find out how many items are in a list using the function len():
list = [2,4,8]
print(len(list))
Does this return a result that is a string or an integer? Find out.
And if you wanted to refer to a specific item in the list, you can refer to it by its position in the list, called an index. So if I wanted to call on 4 in the list above, I would type:
print(list[1])
Try it out. Why do you think the index position 1 refers to what we perceive as the second item in the list?
Who’s coming to the party: Iterating
Now that we’ve got lists on the table, let’s talk about one more really important thing we can do in Python which is iterate. To iterate means to do something repeatedly for a certain number of times.
Going through a list is a common way to iterate.
Let’s say you had a list of friends and wanted to invite them all to your party. You might do something like this:
def party():
friends = [“Alex”, “Allen”, “Abigail”]
for friend in friends:
print(friend + “ is invited to my party.”)
Notice something pretty cool about Python iteration here:
for friend in friends:
The term “friend” did not exist before you put it in this iteration command. You could also have done it like this: for x in friends or for i in friends or anything in friends that you want to call it. You can refer to your iteration increment as anything, and Python will understand if you data is in a form that you can iterate over. You can also then call it as a variable you have defined (as in print(friend + ...). This helps keep your code human readable.
You can also use in to check for individual letters in strings. So let’s say you were about five years old, and you only wanted to invite friends whose names started with A to your party. You could combine a for loop and a conditional:
partyPooper():
friends = ["Alex", "Allen", "Abigail", "Zachary"]
for friend in friends:
if "A" in friend:
print(friend + " is invited to my party.")
else:
print(friend + " is not invited to my party.")
Now, write your own party invite function. Your friends are Leah, Lily, Landon, Shelley, Thisbe, and Henry. You only want to invite people with an H in their name, but it doesn’t have to be at the beginning. Also, you want to have a count of how many people are coming to your party. The last thing printed should be “X number of people are coming to my party.”
Range
One more common thing to iterate over is a range. We specify a range using a built in a function named range(). range() defines, as the name suggests, a range of numbers. The most basic version of range() takes one parameter, which is the total number of increments you want in your range.
Build this function:
def countup():
for i in range(10):
print i
What do you notice about the range of the numbers that range(10) generates?
Quick review
We’ve covered a few more big bases in this lab:
- Conditionals: if/elif/else, in / not in
- Loops: while, for
- Intro to lists, including len() and index number list[i]
- Iterating over a list and a range
We can do a lot of things with these basic tools. In our next two labs, we’ll be using them to create some computational literature.
Acknowledgements
This lab is based on the outline provided by Jerod Weinman’s Python: Conditionals lab.
