This lab was based on problems created by Dominique Thiebaut and labs created in 2018 by R. Jordan Crouser. This content was remixed and updated in 2019/2020 by Alicia M. Grubb.
In order to be sucessful in computer science, an important skill that you must develop is understanding how to implement and develop a specification, and knowing when you can take liberty with the specification. You also need to distingush between implementing and developing a specification. In the course work for CSC111, we ask for some things very precisely. It is important that you read every word of lab and assignment descriptions. Misreading or ignoring directions will result in incorrect software/code.
Take a few minutes and introduce yourself to your lab partner. Answer the question: “Where do you wish to travel some day?”
We added prompts to remind you to switch driver/navigator roles, but feel free to switch more frequently or mid task.
for...in
) loopsA definite loop is a loop where you know exactly how many times the loop is going to run before you start.
In Lab 1: Introduction to Python, we wrote a loop that looked like this:
for name in [ "Aleah", "Belle", "Chen" ]:
print(name)
Without even typing the code into the shell
, we can tell that the code inside the loop is going to execute
exactly 3 times: * once for "Aleah"
* a second time for "Belle"
* and a third time for "Chen"
Type the code in the shell and verify your hypothesis of what it does.
We could also write a loop that iterates over list of numbers (in the shell):
for x in [ 1, 2, 3, 4, 5 ]:
print(x)
Looking at the list above, we can tell that the loop is going to execute five times (once for each element in the list).
range()
functionThe range()
function provides a quick way to generate a list of numbers in Python. This is particularly useful when we want to loop a set number of times, or over a list of numbers that have a particular pattern (but we don’t want to type them manually).
range()
function worksTry running the loops below in the Python shell. Feel free to play around with the numbers, and see if you can get a feel for how range()
works:
# Loop 1: range() with one value
for n in range( 10 ):
print(n)
# Loop 2: range() with 2 values
for n in range( 5, 10 ):
print(n)
# Loop 3: range() with 2 values, starting at a negative value
for n in range( -1, 4 ):
print(n)
# Loop 4: range() with 3 values
for n in range( 1, 10, 2 ):
print(n)
# Loop 5: range() with 3 values, last value negative
for n in range( 10, 0, -2 ):
print(n)
Create a new file/document in Thonny and save it locally with the file name lab3p1.py
. Add the course header with the relavent information.
Write the following three loops:
Even numbers:
Write a loop that prints all the even numbers between 0 and 20.
Multiples of 3:
Write a loop that prints all the multiples of 3 between -20 and 20.
List odd numbers in reverse order:
Write a loop that prints all the odd numbers starting at 9 and going down to (and including) 1.
counter
Let’s start with a simple list-controlled loop:
for animal in [ "dog", "cat", "horse", "chicken" ]:
print(animal)
Now imagine we wanted to count the number of times we have gone through the loop. We can do this by defining a variable
and incrementing its value each time the loop runs:
# Initialize the counter to 0
counter = 0
# Run through the loop
for animal in [ "dog", "cat", "horse", "chicken" ]:
counter = counter + 1 # +1 each time the loop runs
# Print out the (updated) value of counter
print("The loop ran", counter, "times.")
Create a new file/document in Thonny and save it locally with the file name lab3p2.py
. Add the course header with the relavent information.
Add the above code snippet to lab3p2.py
. Without running the program, figure out what the output of the program is. Discuss this with your lab partner. When you both agree, add a comment (called # Hypothesis
) describing the purpose of the code snippet. Then run the code and verify your hypothesis.
Next, modify the program to print
the value of counter
as well as the animal
, so that its output looks something like this:
Animal 1: dog
Animal 2: cat
Animal 3: horse
Animal 4: chicken
At this point you should switch driver/navigator roles.
while
) loopsIn addition to for
loops (where we know in advance exactly how many times we’re going to repeat), sometimes it is helpful to be able to loop until some condition is met.
For example, the following code prints out all positive square numbers less than 200:
n = 1
while(n**2 < 200):
print(n, "*", n, "=", n**2)
n+=1 # increment n
These kinds of loops (called indefinite loops) are frequently used in combination with user input, because we don’t know in advance how many times the user will need the code to repeat.
Create a new file/document in Thonny and save it locally with the file name lab3p3.py
. Add the course header with the relavent information.
Create a simple guessing game that asks the user to “Guess an integer between 0 and 9:”, and then tells them either “Nope! Try again…” when the user’s guess is incorrect, or “CONGRATS! The secret number was X” when the user’s guess is correct (where X is the value of the secret number).
Begin your program by selecting a random number using random.randint
. Run your program several times to notice how it works and verify if it is correct.
In this challenge, you’ll write a python program that asks the user to enter a name, email address and phone number, and then outputs it back on the screen. If desired, the program then repeats the process.
Create a new file/document in Thonny and save it locally with the file name lab3p4.py
. Add the course header with the relavent information.
input()
function to collect the user’s first name, last name, email address, and age.NO
, then print Goodbye!
Here is an example of what your program might look like when it is run:
First name: **Allie**
Last name: **Gator**
Email address: **allie@gator.com**
Phone: **222-222-2222**
+-------------------------+
| Name: Allie Gator |
| Number: 222-222-2222 |
| Email: allie@gator.com |
+-------------------------+
Enter another contact (YES/NO)? **YES***
First name: **Croc**
Last name: **O'Dile**
Email address: **smile@lots-of-teeth.com**
Phone: **123-456-7890**
+---------------------------------+
| Name: Croc O'Dile |
| Number: 123-456-7890 |
| Email: smile@lots-of-teeth.com |
+---------------------------------+
Enter another contact (YES/NO)? **NO**
Goodbye!
Note: the information entered by the user is surrounded by **asterisks** just to highlight it - your user does not need to enter them.
Create a new file/document in Thonny and save it locally with the file name lab3p5.py
. Add the course header with the relavent information.
“Old MacDonald’s Farm” is a song most American kids learn at one point in their life. If you don’t know it, this YouTube video will get you acquainted with it. :-)
The goal of this problem is for you to print
the lyrics to the famous song using a for loop
on a list of animal:sound
pairs provided by the user. To do this, you’ll need to bring together your knowledge of user input, loops, and string operations.
Ask the user to enter a set of animal:sound
pairs (separated by commas) using the input()
function. Their input might look something like this:
Enter a set of animal:sound pairs (separated by spaces): **dog:woof cat:meow horse:neigh chicken:cluck**
Note: again, user input is surrounded by **asterisks** for emphasis only.
Separate the input string
into a list of strings containing animal:sound
pairs.
Separate each animal:sound
pair into an animal
and a sound
(hint: the .split()
method can take a parameter specifying which character to use for the split).
Finally, print the lyrics of “Old MacDonald” using the user input. Your goal is output that looks like this:
Verse 1 - DOG
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a dog, E-I-E-I-O
With a woof woof here and a woof woof there
Here a woof, there a woof, everywhere a woof woof!
Old MacDonald had a farm, E-I-E-I-O
Verse 2 - CAT
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a cat, E-I-E-I-O
With a meow meow here and a meow meow there
Here a meow, there a meow, everywhere a meow meow!
Old MacDonald had a farm, E-I-E-I-O
Verse 3 - HORSE
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a horse, E-I-E-I-O
With a neigh neigh here and a neigh neigh there
Here a neigh, there a neigh, everywhere a neigh neigh!
Old MacDonald had a farm, E-I-E-I-O
Verse 4 - CHICKEN
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a chicken, E-I-E-I-O
With a cluck cluck here and a cluck cluck there
Here a cluck, there a cluck, everywhere a cluck cluck!
Old MacDonald had a farm, E-I-E-I-O
lab3p1.py
through lab3p5.py
files before the end of the day.If you have time, we encourage you to get started on your homework assignment in lab this week.