Python Conditionals and Repetition
CSC 105 - The Digital Age - Weinman
- Summary:
- In this laboratory, you continue the journey and joy
of learning to write computer programs in the Python programming language
by utilizing conditionals and more repetition (it's a good thing).
So far, all the functions we have written work by executing each statement
in the function in order, from top to bottom. To write programs that
solve more complex problems, we need mechanisms that will allow statements
to be executed in more complex ways. For example, we might like to
execute some statements under some conditions but not others, or we
might like to execute some statements multiple times. These require
our algorithmic ingredients of conditionals and repetition.
A. Preparation
- Open a terminal window and launch the Calico program by typing (or
pasting) the following command
-
/opt/Calico/calico &
- In the Calico window that opens, click the Shell tab. You
should see a blank white window with a python> prompt and
a blinking cursor.
- In the tab titled "New Python Script", enter comments (lines beginning
with # for you and your partners names, and the title of
this lab).
- Save the file in your 105 folder as condLab.py
Conditionals: if
The reading (re)introduced the if statement, which allows
us to write conditional behavior into our program. This flexible algorithmic
control structure gives us a lot of power. In its simplest form, we
could write
-
if <something is true>:
<do something>
<do another thing>
...
What if we want to elect to choose between one of two actions? 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>
...
Finally, some of our decisions may 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 the first two (at least) into practice.
B. Making Decisions
In this exercise, we will explore programs that determine which statements
should be executed based on the values of variables.
- Enter the following procedure in your script.
-
def isPositiveInput():
number = float(input("Enter a number: "))
if number > 0:
print("That number is positive")
- Save and run the script, and try running your function from the Shell.
python> isPositiveInput()
- Now add a second print statement (with any message you want)
at the end of the function, being careful to indent it by the same
amount the first print statement is indented. How does this
affect the output of your function when you enter various values?
- Now try removing the indentation from the second print statement.
(In other words, leave the first print statement where it
is, but move the second back to be aligned with if toward
the beginning of the line.) How does this affect the program's output?
If all went well, you should have discovered that when python encounters
an if statement it checks whether the associated condition
(in this case, number > 0) is true. If it is, python executes
all statements that immediately follow the if clause and
are indented beneath it. If the condition is false, these statements
are skipped. In either case, execution will then continue with the
next un-indented statement.
- The example above uses one relational operator (greater than,
>), but Python has several more as shown below.
| Operator | Meaning |
| < | less than |
| <= | less than or equal to |
| > | greater than |
| >= | greater than or equal to |
| == | equal to |
| != | not equal to |
Notice in particular that to ask whether one value equals
another value, you must use two equals signs, not one. For example,
we could say:
-
number = float(input(Enter a number: ))
if number == 0:
print("You entered 0.")
- The if statement and relational operators work for comparing strings
just like they do for comparing numbers.
Next, write a function called favorite that asks the user
to enter a color name. If the color entered happens to be your favorite
color, print a message to that effect. Otherwise, do not print any
response. (Be very careful with punctuation in this program. The if
line must end with a colon, or python will complain.)
Notice that to check whether your program works correctly, you will
now have 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.
- Let's use these tools and some from the reading to begin making the
robot take a walk whose parameters are partially dictated by the user
and partially by chance.
Add the following lines to your script below the introductory comments
but before any function definitions
-
from Myro import *
from random import *
initialize("/dev/rfcomm0")
In separate tabs, you may want to open the Myro
function reference to remind yourself about how to give the robot
commands you've learned and the Python
overview to remind yourself about how to structure these commands.
-
Begin a function called perambulate
that takes no parameters. The function should
- Move the robot forward at full speed for 1 second
- Get a random integer that is either zero or one
- Print that integer along with a simple message for context (you may
need to use str to convert the integer to a string)
- If the random integer is zero,
- your function should say (that is, speak) "left"
- the robot should turn left at full speed for 0.5 seconds, and
- Otherwise,
- your function should say (that is, speak) "right"
- the robot should turn right at full speed for 0.5 seconds, and
- Your robot should beep for 0.25 seconds at a random frequency between
100 and 1000 Hz.
- Save and run your script. Turn on your robot. Test your perambulate
function for the expected behavior.
C. Repetition
Another useful way to adjust the control flow of a program is by repeatedly
executing statements. We examined the for loop in a previous
reading and lab.
- Let's remind ourselves how to use for and range
for repetition with a warm up problem. Write a function called squares
that prints a table of the first nine positive integers and their
squares. (Once again, be careful to include the colon at the end of
the for statement, or Python will complain.) Your output
should look similar to the following:
Num Square
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
- Now let's add some repetition to your perambulation function.
Modify the function to accept a single parameter called numSteps
which dictates how many times the sequence specified in B.7
occurs. For example, if the value given was 3, the robot would
- move forward, speak/turn, and beep
- move forward, speak/turn, and beep
- move forward, speak/turn, and beep
- Save and run your script. Test your modified perambulate
function for the expected behavior.
D. Aside: Compound data
The end of our reading in chapter three suggested that rather than
using range to generate values over which to step in a for
loop, you could use more arbitrary values, such as [3, 2,
6], or [3.5, 7.2, 1.45], or ["United",
"States", "of", "America"]. In Python, each of these
three structures is called a list. These important collections
allow us to gather data together for common purposes. For example,
we might define the following variable, which contains the eight pitches
of a one octave musical scale:
-
pitches = [523, 587, 659, 698, 783, 880, 987, 1048]
- Copy and paste this definition into your Shell so we can
experiment. (Press enter to execute the line)
- We can extract individual values from the list with so-called subscript
indexing using square brackets; the ith item in the list would
be denoted pitches[i]. The syntax looks very similar
to a function call, except we are indicating with a number how many
items, counting from the beginning of the list to step through before
finding the value of interest. Which pitch frequency do you expect
to get when you type pitches[1]? After making your prediction,
verify it by typing that into the Shell.
- Did you get what you predicted? If so, congratulations on reading
carefully. If not, that's ok. Note that the index of each item corresponds
to the position in the list, counting from zero. What do you expect
pitches[0] to produce? After making your prediction,
verify it by typing that into the Shell.
- Note there are 8 pitches in the scale. What do you expect to get if
you type pitches[8]? After making your prediction, verify
it by typing that into the Shell.
- Did you get what you predicted? If so, congratulations on reading
carefully. If not, that's still ok. Remember that we count from zero,
so to exhaust all the items in the list, we are at an index that is
one less than its length. What do you expect pitches[7]
to produce? Verify your prediction.
- We can find the length of any list with the following Python function
-
len(<name of list>)
Use this function to calculate the length of pitches in the
Shell.
- What do you expect pitches[len(pitches)-1] to produce?
Verify your prediction.
- To summarize, what is the range of valid indices for pitches?
- Add the definition of pitches near the top of your script
after the initialize() command.
- Using your answer to that question, write a function called playNotes
that takes a list of frequencies as a parameter and plays each note
in the list for 0.5 seconds. Your solution will start like this
-
def playNotes(notes):
for index in range(0,
- Save and run your script before testing your function. In
addition to pitches, here is a different list of
notes to test your function with.
-
playNotes([523,659,783,1048,783,659,523])
If you get an error, you will need to generalize your second parameter
to range using the len function.
E. Mixing conditionals with repetition
We can place any valid Python statement inside either a for
or while loop or an if statement. Among other things,
this means that we can place loops within loops, or conditionals within
conditionals. Similarly, we can place conditionals within loops, and
vice-versa. This flexibility allows us to solve many complex problems.
In this exercise, we will solve more problems that require us test
a condition multiple times.
For later use, add the definition of pitches (given above)
to your script below the initialize command.
Now you will write a function called whistle(notes) that
takes a list of frequencies as a parameter and randomly beeps from
those frequencies at random varying durations until it choose the
same note twice.
- Begin by writing the definition line of the function.
- To indicate the next pitch to beep, declare a variable called nextIndex
and give a random index from the list of notes.
- To indicate the previous pitch beeped, declare another variable called
lastIndex and give it (initially) the value 0.
- Inside a while loop that checks whether the last index is not the
same as the next index to beep,
- Get another random integer between 1 and 3. If that number is 1, beep
the frequency at nextIndex of notes for a full second.
Otherwise, beep it for just a half second.
- Update lastIndex to the index of the note you just beeped.
- That's it! Save and run your script. You can test it with the value
for pitches.
F. Putting it all together
Once you've got everything else working, let's note the power of abstraction
when building complex systems.
- Replace the beep in the last line of perambulate
with a call to whistle(pitches).
- You should now have a randomly walking and whistling robot! Save and
run your script, testing it out.
- How much more complicated would perambulate be if, instead
of calling whistle as a separate function, you simply literally
copied and pasted the code for whistle into perambulate.
Would the code be as easy to understand?
This derivative work in B.1-B.5 and C.1 was originally
authored by Marge Coahran.
Copyright © 2015 Jerod
Weinman.
This work is licensed under
a Creative
Commons Attribution-Noncommercial-Share Alike 4.0 International License.