Laboratory: Programming in Python (Conditionals and Repetition)
CSC 105 - The Digital Age
Summary: In this laboratory, you continue the journey of
learning to write computer programs in the Python programming language.
Contents
Open a terminal window, and move to the code directory you created in the
first Python lab, and then open gedit as shown below.
As before, you will move back and forth between these two windows, writing
programs in gedit and running them in the terminal window.
cd 105/code
gedit &
Next, please quickly review the previous lab so that the lessons you learned
there will be fresh in your mind for you to use today.
So far, all the programs we have written work by executing each
statement in the program 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.
In this exercise, we will explore programs that determine which statements
should be executed based on the values of variables.
a.
Please copy the following program into a file called sign.py
and run it a few times, entering different numbers each time.
You should find that if you enter a positive number, a message is printed
to that regard, but if you enter a negative number or zero, no message prints.
number = input("Enter a number: ")
if number > 0:
print "That number is positive."
Note that the indentation of the print statement should be
made by pressing the TAB key once.
Now add a second print statement (with any message you want) at the
end of the program, being careful to indent it by the same amount the
first print statement is indented. How does this affect the output of
your program 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 at 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.
b.
The example above uses one relational operator (greater than), but
Python has several more as shown below.
Operator | In English |
< | less than |
<=
| less than or equal to |
>
| greater than |
>=
| greater than or equal to |
==
| equal to |
!=
| equal not 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 = 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 program called favorite.py 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 clause 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.
Now add one statement to your program that will cause it to print "Goodbye!"
just before it ends, regardless of the color entered.
c.
Let's return to the program sign.py. Suppose we want to print one
message when the test condition (number > 0) is true, and a different
message when the test condition is false.
We can do that by adding an else clause as shown below.
Please modify your copy of sign.py in this way, and do some
experiments to convince yourself that it works. (Again, you must be
careful to include the colon after else.)
number = input("Enter a number: ")
if number > 0:
print "That number is positive."
else:
print "Definitely NOT positive."
print "This message prints every time."
d. Now return to favorite.py and modify your program 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.
Another way to modify the control flow of a program is to have it
execute one or more statements repeatedly.
a.
Please copy the following program into a file called loops.py, and
then run it to see what it does.
count = 1
while count <= 5:
print "Grinnell"
print "College"
count = count + 1
print "Done"
How many times are "Grinnell" and "College" printed? How many times
is "Done" printed?
Now let's walk through the program to understand how it works. On the
first line we create a variable named count and set it equal
to one. The next statement contains a test condition ( count
<= 5 ). This condition will be evaluated, and if it is
true, the statements indented beneath it will be executed. Once that
has happened, execution returns to the top of the
while loop, where the condition is checked again. This
process will continue, with the indented statements being executed
repeatedly as long as (i.e.,
while) the condition continues to be true. If the condition is
ever false when it gets checked, execution will jump to the first statement
after those associated with the loop (the first un-indented statement).
The careful reader will notice that it is important for something about
the condition to change on each pass through the loop.
What will happen if you remove the statement
"count = count + 1"? Remove the statement to verify your
prediction.
If all went "well", you should have discovered what programmers call
an infinite loop. This means your program will continue
running forever, unless you stop it from outside. You can do this by
typing Control-c in the terminal window where the program is
running. (Go ahead and stop the program now.)
Modify the program loops.py so that it prints some word or
phrase nine times, and also prints a line number at the beginning of
each line. For example, your output might look like the following:
1 Python
2 Python
3 Python
4 Python
5 Python
6 Python
7 Python
8 Python
9 Python
IS FUN!
b.
Write a program called squares.py that prints a list of the first nine
positive integers and their squares. (Once again, be careful to include the
colon at the end of the while statement, or Python will complain.)
Your output should look similar to the following:
Number Square
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
c.
Write a program called blastoff.py that counts from 10 down to 1,
and then prints "Blastoff!" Your output should look like this:
10
9
8
7
6
5
4
3
2
1
Blastoff!
d.
Write a program that asks the user to enter three numbers: a starting value,
an ending value, and an increment. Your program should then "count" based
on these criteria, as shown in the example below.
This program counts for you.
Enter the starting value: 3
Enter the ending value: 13
Enter the increment: 2
3
5
7
9
11
13
We can place any valid Python statement inside either a
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 problems that require us to make a
given decision multiple times. We can do this by placing an
if
statement within a loop.
a. Write a program that uses a while
loop to
print the output shown below. As you can see, the program should print
the numbers 1 through 10, except that between 7 and 8 it should print
the word "happy". This can be accomplished by placing an if
statement
within the while
loop to do something special for the
lineNumber == 7 case.
1
2
3
4
5
6
7
happy
8
9
10
As mentioned above, we can have one loop inside the body of another
loop. The following Python program prints a (not very pretty)
"multiplication table" to the terminal window.
import sys
numOne=1
while numOne<10:
numTwo=1
while numTwo<10:
product = numOne*numTwo
sys.stdout.write( str(product) + " " )
numTwo=numTwo + 1
numOne=numOne + 1
print
You can copy this program to your directory with the following command
in the terminal window:
cp ~weinman/courses/CSC105/labs/times.py ./
Note that because the Python print procedure tries to
do too much for us with respect to putting output on new lines and
adding spaces after we print, we have switched to using a
write procedure, which only prints exactly what we
ask it to print. As a result, only the product number and a space
get printed, while the very last print line within the
first loop moves the subsequent output to the next line.
In order to add that functionality to our program, we had to start
it with the command import sys
.
Try to make a few other observations about how this works by
answering the following quetions.
-
Why is numTwo reset to 1 at the beginning of the "outer" (top-most)
loop?
-
What would happen if this line was removed from the program?
-
Test your prediction by "commenting" out the line. Commenting a
line means that the interpreter ignores it, not trying to run it
as program code. You can do this by adding a # to the
beginning of the line.)
-
Why is numTwo incremented in the body of the "inner"
loop?
-
What would happen if this line was moved to the "outer" loop
(e.g., by removing one of the tabs from its indentation)?
-
Hopefully, you should see that since numTwo would never
change, the condition of the second while loop would always remain
true, and we'd have another infinite lop.
-
Why are there two different "count" variables for the nested
loops? In other words, why wouldn't the following work?
...
while count<10
...
while count<10
...
count=count+1
...
count=count+1
The answer to the last question is that there is only one count
variable for both loops. Any time count is modified in
the inner loop, the value is also modified for the outer loop, and
vice-versa. Thus, this code does not have the effect we want, which is
to have two loops with two independent counters. This principle will be
important for the next lab, so make sure you understand it clearly!
a.
Write a program that plays a familiar guessing game: first your program
will set some number to be the "correct answer", then your program will ask
the user to guess this answer until they get it right. For each guess your
program should give a hint based on whether the guess was too high or
too low.
For example, a session with your program may look like the following:
Enter your guess: 46
Your guess is too low
Enter your guess: 97
Your guess is too high
Enter your guess: 62
Your guess is too low
Enter your guess: 88
Your guess is too high
Enter your guess: 82
CORRECT! You Win!
Hints:
-
Begin your program with a line similar to: answer = 82. In a
real game we would want to begin with a random number, but for today
let's pick a single number that will always be the correct answer.
-
This program will require a loop with some if-statements inside it.
-
Each time through the loop, you must accept a new guess from the
user. This can be done by adding an input statement as the last
statement within the loop.
-
How will you know when to stop looping? When the guess is your answer.
b.
Write a program that reads in three strings and prints them out in
alphabetical order. For example,
Enter a word: hello
Enter a word: goodbye
Enter a word: zebra
In alphabetical order: goodbye hello zebra
Hints:
-
String comparisons, such as word1 < word2, work by
comparing the ASCII values of the characters in the two
strings. This means that word1 will be considered "less
than" word2 if it comes first alphabetically. (Well
almost. The ordering can be surprising if we compare capital letters
to lower-case letters because all ASCII codes for capitals precede
all codes for lower-case letters. I suggest you only enter
lower-case words when running your program.)
-
This problem only requires if-statements, but your condition will
need to be more complex than we have used before. A compound
condition is one that includes multiple parts. Here are two
examples. You may find that something similar will be useful in this
program.
if number > 2 and number < 10:
**do something interesting here**
if word1 > word2 and word2 > word3:
**do something interesting here**