Lab 3 - Loops & Lists Intro
Directions for Labs
- Submit your completed lab file online to CourSys (not Canvas). Labs are marked on completion, not correctness, so complete each part to the best of your ability and learn!
- It is recommended that students attend in-person lab sections for lots of help!
- If you would like to attend an in-person lab section, you are welcome to come to any (or more than one) lab section.
- There is no need to attend the section you are enrolled in.
- There is no need to attend any lab sections: there is no attendance taken.
- You can complete the lab on your own time or own computer if you like.
- While completing these labs, you are encouraged to help your classmates and receive as much help as you like. Assignments, however, are individual work and you must not work with another person on assignments.
Loop to Favourite Number
- Inside your
cmpt120
folder, create a new folder forlab3
and make alab3.py
file.- See lab 1 for more detailed directions.
- Reminder: You should always open your
cmpt120
folder in VS Code each time and then browse in VS Code to find your lab files. By always opening the fullcmpt120
folder you'll always have access to your files.
- Ask the user to input their favourite number:
- Remember that
input()
gives you a string, but here we'll need an integer. - Hint: Use
int(...)
to convert a string to an int. - Hint: You might have code similar to:
fav_number = int("42")
(but not hard-coding the string).
- Remember that
- Write a loop that prints all numbers from 0 up to one less than the user's favourite number.
- Hint: Remember
range(n)
. - Hint: You'll need a
for
loop. - Hint: Remember to indent all the code you want to execute as part of the loop.
- Hint: Write a little code, test a little code.
- Hint: Remember
- Change your loop (above) to make it count from 1 up to the user's favourite number.
- Hint: Normally our loops go from 0 to n-1, so inside the loop when you print you'll need to +1.
Find Multiples of the Favourite Number
- Change your loop above to loop between 1 and 50 (inclusive):
- Create a named constant to hold the 50 vs using magic numbers:
MAX_LOOP = 50
Use this constant in your loop. - Hint: Loop may look like:
for i in range(MAX_LOOP):
- Create a named constant to hold the 50 vs using magic numbers:
- Change the loop so that in addition to printing out the number, it also checks if the number is a multiple of the user's favourite number. If it is, print "Multiple!".
- For example, if the user enters 15, the program will go through all numbers between 1 and 50 as before but also for the numbers 15, 30, and 45 it will say that they are multiples of the user's number.
- Hint: % gives the remainder when doing integer division.
- Hint: If the remainder when performing
x % y
is 0, thenx
is a multiple ofy
. - Hint: Use an
if
statement to check if the remainder is zero. For example:if i % fav_num == 0: print("...")
- Store a list of multiples of the user's favourite number:
- Every time you find a new multiple of the number, add that number to a list of numbers.
- Hint: See the mind reading example we did in class to add an element to a list.
- Hint: Recall we used code like:
my_list.append("apple")
to add "apple" to the list namedmy_list
. - Hint: You'll be adding number rather than a string.
- Hint: You'll want to create an initial empty list before your loop. It might look like:
my_list = []
(but you should name it better thanmy_list
)
- When finished looping through the numbers between 1 and 50, print out a summary, such as:
For 15, there are 3 multiples = [15, 30, 45]
- Hint: In the output string, where do each of the numbers come from? (The 15 is the user input, the 3 is how many elements there are in our list, and the list is just printing the list).
- Hint: To find out how many elements are in a list, use
len(my_list)
. - Hint: Use an f-string to create this string to print.
- Hint: To easily print a list named
prime_numbers
, you could use:print(" Here are the primes:", prime_numbers)
- Hint: To print a list using an f-string, use something like:
print(f"My data is {my_list}")
- Understanding:
- What is a benefit of using a named variable (a "constant") to hold the 50 vs typing it into the code?
- Hint: Think about if you needed this value more than once.
- Hint: What advice was given in class about writing code more than once or twice?
- When items are added to our list using
append()
, are they added to the front or the back? Test this. - What is the test to see if a number is a multiple of another number? How is it written in Python?
- What is a benefit of using a named variable (a "constant") to hold the 50 vs typing it into the code?
Summing Multiples
- Compute the sum of all the multiples of the user's favourite number between 1 and 50.
- Hint: Use the accumulator pattern discussed in lecture.
- Hint: Create a variable (the sum/accumulator) outside of a loop, and then loop through all elements of the list adding each one to the accumulator variable.
- Hint: You have a list of multiples already, so now use a
for
loop within
to loop through. - Hint: Your code may look like:
for da_thingy in da_multiples_list:
- Hint: When you are done your loop, the variable should hold the sum of all the multiples.
- Next, let's print something profound (not really) about what we have calculated:
- Let's use
n
to refer to how many multiples were found, and let's uses
to refer to the sum of all the multiples. Then:- When
n
>= 10: ifs
> 500 print "Prolific and big", otherwise print just "Prolific".
(Note: Correction made here to compare against 500. No points lost if your solution uses 50 or 500.) - Otherwise, when
n
< 10, just print "Only a few."
- When
- Hint: Try using a nested
if
. - Hint: Your "outer"
if
statement will check if the length of the list is >= 10. - Hint: Your "inner"
if
statement will check if the sum of the list is > 500. - Hint: You'll need
else
to handle the "Prolific" and "Only a few." Test your code carefully to ensure it does the right thing. Testing hint: try really small numbers like 1, and move up from there.
- Let's use
Division
- Imagine that the user had written a test for one of their courses (out of 99), and had earned a score on the exam of their favourite number! How lucky!
- Print out what percentage the user would earn on that test, to 1 decimal place.
- Your output may look like:
If you got 42 out of 99 on a test, your percentage would be 42.4%!
- Hint: Compute the percentage before displaying it.
- Hint: Use an f-string to print out the floating point value.
- Hint: An example f-string might look like:
pi = 3.1415 print(f"Pie is {pi:0.3f}!")
Submission
Submit your lab3.py
file to CourSys by Sunday midnight. Remember you can submit up to 3 days late with no penalty if needed (but please plan to get it done on time to stay up to date on the course!)
Topics Covered
for
,range(n)
- Loop to reduce code duplication
str(...)
,int(...)
:- Read input, convert to integer, do math, convert to string.
- Accumulator pattern
- Nested-if
- Math
- Division gives floating point value
- % for mod (remainder)
len(mylist)
- f-Strings
- Format output of floats using f-string literals