Homework 1: Python fundamentals#
And using external resources to better understand code!#
✅ Put your name here#

Learning Goals#
Content Goals#
Review the arithmetic operators in Python
Utilize loops to perform repeated operations and to store, access, and manipulate data in one more or lists
Utilize variables and lists to store and access data
Use conditional statements to control code flow.
Practice Goals#
Use the internet as a resource for learning how to write code, learn new things, and troubleshoot problems
Solve a variety of problems using code
Troubleshoot errors and debug your code as issues arise (you’ll do this all the time in this course!)
Assignment instructions#
Work through the following assignment, making sure to follow all the directions and answer all the questions.
NOTE: If you are using content to solve problems that has not been covered in our pre-class or in class assignments, you MUST cite your work. This includes any use of the resources reviewed in Day 4. We have not yet discussed responsible use of generative AI, so you are not encouraged to use it at this time (wait for Day 7!). However, if you do use generative AI tools, you must indicate which tool you used and what lines of code were produced by generative AI and which ones were produced by you. Failure to properly cite your work may result in loss of points on the problem.
This assignment is due at 11:59 pm on Sunday, Sep 14th. It should be uploaded into the “Homework Assignments” submission folder for Homework #1. Submission instructions can be found at the end of the notebook.
Version check#
Before you begin, make sure your Jupyter kernel is Python 3. There are significant differences between Python 2 and Python 3, and we use Python 3 in this course. The kernel type at the upper-right corner should say “Python 3”, and the following code should show a version of the form: 3.x.y (where “x” and “y” are the sub-version numbers).
If your kernel is Python 2, try selecting Python 3 from the Kernel menu above under the sub-menu “Change kernel”. If that does not work, consult the Teams help channel for assistance.
import sys
print(sys.version)
Grading#
Integrity statement and office hours
Academic Integrity Statement (2 points)
Going to Office Hours (8 Points)
Doing basic math with Python (14 points)
Storing and accessing data using lists (10 points)
Writing for loops in Python (27 points)
Writing while loops in Python (11 points)
Writing if statements in Python (9 points)
Total points possible: 81
0.1 Academic integrity statement (2 Points)#
In the markdown cell below, paste your personal academic integrity statement. You should have generated this in the Day 4 pre-class assignment, if you did not do this pre-class assignment, locate that assignment, find the appropriate section, and draft your integrity statment now.
By including this statement, you are confirming that you are submitting this as your own work and not that of someone else.
✎ Put your personal academic integrity statement here.
0.2 Going to Office/Help Room Hours (8 Points)#
Why are we doing this?#
We want to make sure that everyone knows how to access the resources available to you. One of the best resources you have at your disposal is office/help room hours, which are offered by the instructors, TAs, and LAs associated with CMSE 201.
What will you do?#
(At minimum) Go to one office hour session â(it doesnât matter which one you go to). Come with one question that you would like to talk about. It can be big or small. Ask your question. All of the instructional staff for CMSE 201 (section instructors, TAs, and LAs) will have access to a roster of the folks enrolled in CMSE 201 and will be able to mark off that you stopped in. As long as there ends up being a check next to your name, youâll get credit for this part of Homework 1.
If your schedule is such that none of the nearly 40 hours of office hours/help room work with your schedule, send an email to the CMSE 201 lead instructor, Dr. Robert Termuhlen (termuhle@msu.edu), to coordinate an option to make sure you can get credit for this part of the assignment.
NOTE: Since the homework is due Sunday, September 14th, the office hours on Friday, Sept. 12th will be the busiest time for folks to go to office hours. You are STRONGLY encouraged to go to office hours before that Friday to get credit for this part of this assignment. If you show up to office/help room hours on that Friday and it’s very busy, there is no guarantee that one of the instructors, TAs, or LAs will be able to check you off for this part of the assignment. (You should still feel free to go to office hours on Friday for help, though!)
You can find the office hours calendar on the course website. There is a link to the calendar on the front page. Double-check the calendar events for details on which zoom room or physical location the office/help room hours are being held in. The information is also pinned in the cmse201-FS25-help channel on Teams!
1. Doing basic math with Python (14 points)#
As you explored with your order of magnitude modeling assignment in the Day 2 in-class assignment, Python is great at doing basic math – much like your favorite calculator! As you get more comfortable with writing Python code, you might find yourself writing a bit of code when you need to do some calculations instead of pulling digging out your calculator or launching the calculator app on your phone.
Doing basic math with Python involves using various “operators” – these operators are the Python symbols used to do the actual math. For example, to add two variables, we use the “+” operator. To subtract, we use the “-” operator.
There are a number of other arithmetic (math) operators as well.
✅ Question 1.1 (4 points)#
In the markdown cell below, fill out the following table to indicate what math each operator is used for. If you don’t know the answer off the top of your head, you should practice using Google (or your search engine of choice) to pick up some new Python knowledge (something even the pros do!). Make sure you use the keyword “python” in your search terms when looking for these math operators.
Remember: You can double-click on a markdown cell to edit it.
Arithmetic Operator Symbol |
Name of Mathematical Operation |
Description |
|---|---|---|
+ |
Addition |
Add two variables or numbers together |
- |
Subtraction |
Subtract one variable or number from another |
* |
||
/ |
||
** |
||
% |
✅ Question 1.2 (4 points)#
In the markdown cell below, indicate how you knew each answer in Question 1.1. For example:
If you knew the answer from a previous assignment in CMSE 201, indicate which assignment you learned the material.
If you had to search the internet, indicate which website led you to the correct answer by including the web address and date you accessed it.
✅ Question 1.3 (2 Points)#
Provide an example of where you used an arithmetic operator recently outside of CMSE 201.
Example: I was baking a cake last week, and I had to increase the recipe size to feed 6 people instead of 4, so I had to multiply each ingredient amount by 1.5.
✎ Put your answer here.
✅ Question 1.4 (4 Points)#
Using your mathematics example, use code to demonstrate how you could use Python to perform the calculation.
### EXAMPLE ###
conversion_factor = 1.5
sugar_old = 1 #cups
flour_old = 1.5 #cups
butter_old = 0.5 #cups
sugar_new = sugar_old*conversion_factor
flour_new = flour_old*conversion_factor
butter_new = butter_old*conversion_factor
print('I now need ', sugar_new, 'cups of sugar and ', flour_new, ' cups of flour and ', butter_new, ' cups of butter.')
# Put your answer here
2. Storing and accessing data using lists (10 points)#
The Python list datatype can be a really useful way to store and access data using the functionality that is built into the default version of Python. As the semester progresses, we’ll learn about other Python “libraries” (packages of code designed to do useful things) designed to work with data, but for now, the list datatype is our primary tool.
Creating a list from scratch#
There are a variety of ways you can create a list and fill it with values and you’ll want to make sure you’re comfortable doing this.
✅ Question 2.1 Creating a List (4 points)#
In the cell below, define a list that contains the names of at least 5 titles of your favorite media. These can be books, movies, TV shows, songs, video games, etc. Demonstrate two different ways to create a list with these elements. Finally, print out your list!
# Put your answer here
Accessing and changing values stored in a Python list#
Once we get comfortable with creating lists with some set of initial values, we need to get comfortable with accessing the information stored in the list. The way that we access information is by using an index to access a value at a particular position in the list. Index values are integers that allow you to refer to values at specific positions in the list. The first index is always 0 in Python. So the third element in a list would be accessed using an index of “2”. You’ll just need to get in the habit of thinking this way when working with Python.
Using an index not only allows us to access a value in a list, but it also allows us to update or change values in a list.
✅ Question 2.2 (3 Points)#
Now that you’ve identified different ways to create lists, write some code to access and modify values in the media list created in Question 2.1.
Using your knowledge from CMSE 201, write code that changes the last media entry to the year that piece of media was created. Print the updated list to verify that the results are as expected.
# Put your answer here
Adding or “appending” values to a Python list#
From time to time, we might need to do more than just access and change values inside a list, we might need to add or “append” items to a list. This can be especially useful if our code generates information in a loop and we want to make sure we store that information as we go along. Or, alternatively, we might find situations where we want to append certain information to our list based on a specific condition. In these sorts of situations, the append() function is useful for adding items to a pre-existing list.
✅ Question 2.3 (3 Points)#
Now you’re going to write a bit of code that uses the append() function to add items to a Python list.
Use the append() function to add the names of the creators of the first two pieces of media in your list from Question 2.2. Print the list to ensure the results are as expected.
#Put your answer here
3. Writing for loops in Python (27 points)#
The for loop is a fundamental programming concept in many programming languages. The for loop basically tells the computer to execute the code inside the loop a specific numbers of times. The number of times the loop should be executed can be defined using the range() function or you can tell Python to iterate through sequence of values, e.g. a list, and run the loop until every value has been accessed. We’ll mostly refer to these as “looping by index” or “looping by value”, respectively.
Looping by integers/index#
When we use the range() function in a for loop, we end up generating a set of integer values, which we often use as the index for accessing information stored in a Python container, like a list.
Itâs important to understand how to use these integer index values to access elements of a list in the code that lies inside the loop, but for now we’ll just think about how we can loop over a set of integer values using a for loop.
Looping by value (e.g. through a list)#
Another way that Python allows us to write for loops is by looping through values stored in a sequence of some sort. We often seen this with for loops that iterate through a Python list.
This can be really useful if we have some important data stored in a list and want to go through and do something with each value/item stored in that list. For example, if you had a list of all the students in your section of CMSE 201, you could use a for loop to print out all of their names when you wanted to see the class roster.
Writing a loop that accesses list values using integers or “by index”#
You can use the integer-based for loop approach to index values in a list inside a loop.
If you find yourself in a situation where you need to do a set of repeated operations on using more than one list at a time, using this integer or index-based approach can be really valueable.
✅ Question 3.1 (4 Points)#
Write a for loop that takes an empty list and appends the numbers one through 99 to the list. When you have finished the for loop, print out your list as a way to check if your loop worked correctly.
#Write your code here!
✅ Question 3.2 (2 Points)#
Now, use any method you like to find the sum of this list you created. Make sure you either provide the code you used to find the sum, or you provide a full explanation of how you calculated the sum. For example, I might say my sum is 501 and I got this by adding them all together in my head.
#Write your answer here
✅ Question 3.3 (3 Points)#
Now, calculate the sum of your list again, but this time calculate the sum by using a for loop to go through each value in your list and adding them together keeping track of the running total. Print out your sum when you have finished the loop. If you happened to calculate your sum in this manner already in question 3.2, then find a different way to calulate the sum now.
#Write your answer here
✅ Question 3.4 (1 Point)#
For this question, please compare how you calculated the sum of your list in question 3.2 to how you calculated your list sum in question 3.3. What are some similarities? What are some differences? Which one was easier?
✎Write your answer here:
✅ Question 3.5 (1 Point)#
Create a list called Makeup_Brands and place these items in the list in this order: ‘Huda Beauty’, ‘Rare Beauty’, ‘Maybelline’, ‘Fenty Beauty’, “L’Oreal”, ‘Makeup by Mario’, ‘Haus Labs’, ‘Kylie Cosmetics’, ‘e.l.f.’, ‘NARS’, ‘Urban Decay’, ‘Dior’, ‘Patrick Ta’, ‘ONE/SIZE’, ‘Lancome’, ‘Kosas’, ‘Milk’.
#Write your answer here!
✅ Question 3.6 (2 Points)#
Now write out each value in the list Makeup_Brands that corresponds to the following indices: 1, 4, -1, 8, 0, and 16.
NOTE: Remember that python starts indexing at 0 rather than 1. Indices is the plural form of index.
✎Write your answer here:
✅ Question 3.7 (1 Point)#
Now write out each index in the list Makeup_Brands that corresponds to the following values: Urban Decay, Haus Labs, and Kosas
✎Write your answer here:
✅ Question 3.8 (4 Points)#
Now let’s put this into a for loop. In the following code cell, we provide a for loop that loops by index rather than value. Your job is to dissect and describe each part of the code. What does the range function do? What does the len function do? what does taking the range(len(Makeup_Brands)) do? What is i or what does it represent?
for i in range(len(Makeup_Brands)):
print(i)
✎Write your answer here:
✅ Question 3.9 (6 Points)#
Below you will find a list called Ratings that contains 5 values (ratings out of 5 stars) for each makeup brand in our Makeup_Brands list. Using a for loop, print out the name of each makeup brand and the average rating of that makeup brand calculated from the list of ratings. Your first print out should be Huda Beauty and 3.2
Ratings=[[3.5, 2.0, 4.5, 1.0, 5.0],
[4.0, 1.5, 3.0, 2.5, 4.5],
[1.5, 5.0, 2.5, 3.0, 1.0],
[5.0, 3.5, 1.5, 4.0, 2.0],
[2.0, 4.5, 3.5, 1.0, 3.0],
[3.0, 1.5, 5.0, 4.0, 2.5],
[1.0, 4.0, 2.5, 5.0, 3.5],
[4.5, 2.0, 1.5, 3.0, 1.0],
[5.0, 3.5, 4.0, 1.5, 2.0],
[2.5, 1.0, 3.5, 5.0, 4.5],
[4.0, 2.0, 1.5, 3.5, 5.0],
[1.5, 3.0, 4.5, 2.5, 1.0],
[3.5, 5.0, 2.0, 1.0, 4.0],
[2.0, 1.5, 3.0, 4.5, 5.0],
[1.0, 4.5, 5.0, 3.5, 2.5],
[5.0, 3.0, 1.5, 2.0, 4.0],
[4.5, 1.0, 3.5, 5.0, 1.5]]
#Write your code here!
✅ Question 3.10 (3 Points)#
As it turns out, I don’t like the 5 star rating system. I prefer the 10 star rating system. Using a for loop, modify each value in the Sample_10_star_rating list and multiply it by 2 so that I can see what the rating looks like out of 10 stars. Be sure to print out Sample_10_star_rating after you have modified the values.
#Write your answer here!
Sample_10_star_rating= [3.5, 2.0, 4.5, 1.0, 5.0]
✅ Question 3.11 FOR FUN NO POINTS#
As an extra challenge, try and modify the entire Ratings list using a for loop so that it is multiplied by 2 and is on the 10 star rating scale. This is an extra challenge for fun. You do not need to do this part of the homework. You will not be marked down for not doing this part, and you also won’t be given extra points for doing this part. Do not get hung up on this either. Try it out for fun and if you get frustrated, then move on.
As a hint try printing out Ratings[0][0], Ratings[1][0], Ratings[0][1], Ratings[0][2] to see if this will help access specific values of Ratings.
#Write your answer here!
4. Writing while loops in Python (11 points)#
The while loop is another fundamental programming concept in many programming languages and another “control flow” method. The while loop basically tells the computer to execute the code inside the loop until a particlar condition is met. This means that the number of times the loop is executed may not be immediately known because the conditional statement used to determine when to exit the loop is often dependent on the code that is being called inside the loop.
While using a conditional statement to determine when to stop iterating over the loop can be really useful, it can also be really problematic. A poorly written while loop can result in what is often referred to as an “infinite” or “endless” loop. An infinite loop is a loop that, as you might expect, runs continuously with no end (hence the alternate “endless” name). Infinite loops occur when the conditional statement used in the while loop never becomes False. If the conditional statement is always True, then the loop will run forever.
When using while loops in Python, watch out for infinite loops!. You’ll often notice that you’ve created an infinite loop when you see In[*] on the left-hand side of the cell you just executed for longer than expected. Normally, when a cell finishes running, the * becomes a number. Take a look at your code cells above to confirm this.
If, in this assignment, you’ve found that you created an infinite loop, or suspect that you might have, you can “interrupt” the notebook and stop the code from trying to run. Then you can fix your error and try again. To interrupt your notebook and stop the cell from running, click on the “Kernel” tab at the top of your notebook and select “Interrupt” or, simply click on the black square “stop” button at the top of the notebook.
Looping by condition#
When we use a while loop, we are telling the computer to repeat a block of code until a particular condition is met. The condition may be met with only a few iterations or it may take many iterations. If we’re not sure in advance how many iterations will be necessary, using this condition-based while loop can be a great option.
Important: When deciding to use a while loop to tackle a problem make sure to first ask yourself, does this really require a while loop or would I have better luck with a for loop? It’s important to get into the habit of choosing the right tool for the job!
✅ Question 4.1 (3 Points)#
Write some code that does the following:
Create a
whileloop that runs whilexis greater thany.Inside the loop,
update
xso that it becomes the square of itself,update
yso that it cubes itself,and then print both
xandy.
For starting values, let
xstart at 3 andystart at 1.25.
What is the last value of x where x is greater than y?
# Put your answer here
Now you will run and terminate an infinite loop. We have written a while loop that indefeinitely keeps printing the multiples of 2, namely, 2, 4, 8, 16, 32, 64, …
You should notice that when an infinite loop is running, you will see an asterisk (*) between the square brackets instead of a number like you are used to seeing. That tells you the cell is still running!
To stop the infinite loop, interrupt the kernel as needed as described above (you may also want to restart the kernel!).
#Run this infinite while loop!
x = 2
while x>0:
x = 2 * x
print(x)
✅ Question 4.2 (1 Point)#
Explain clearly why this is an infinite while loop. What makes it loop forever?
✎Write your answer here:
✅ Question 4.3 (5 Points)#
Now that you’ve looked at some examples that use a while loop to interate over some code until a particular condition is met, you’re going to write a bit of code that uses a while loop.
We are going to test our luck with flipping coins. I have always wanted to see 5 heads flipped in a row, but I have yet to have the patience to sit and try for it. Let’s see if we can program this lucky event ourselves with a while loop.
Write some code to do the following:
Write a while loop that flips 5 coins each iteration
The while loop should run until each of those coin flips are all heads. (Let heads be represented by the number 1 and tails be represented by the number 0.)
Print out each set of 5 coin flips
Keep a running tally of how many attempts it takes until you flip 5 heads in a row.
When your while loop has completed, print out the number of attempts it took.
You will be using the random.randint function for this question. The random.randint function will output either a 1 or a 0. We have given you the code that outputs 5 random flips in a list called Flips. You can use this inside of your while loop to generate your 5 random flips each iteration.
import random
# run this cell a few times to get an idea for what this command does
Flips = [random.randint(0, 1) for _ in range(5)]
Flips
[0, 0, 0, 0, 1]
## Write your answer here
tally = 0 # variable to keep track of how many iterations are run
heads = 0 # variable to check how many heads in each iteration
while ??? # <----- Fill this in!!!
Flips = [random.randint(0, 1) for _ in range(5)] # Flip a coin 5 times
??? # <----- Fill the rest of the loop in!!!
✅ Question 4.4 (2 Points)#
Statistically, how many attempts should it take for you to get 5 heads in a row? How does this number compare to what you actually got from your while loop? (Be sure to document how you found your answer and cite any outside sources you use!)
✎Write your answer here:
5. Writing “if” statements in Python (9 points)#
Conditional statements, often referred to as “if” statements, let your code run only when conditions are met. (hence the term “conditional”). Getting used to using if statements, and more complex if-else or if-elif-else statements, is an important part of learning to build evermore complex algorithms.
One of the most challenging aspects of writing if statements is just thinking through the logic of what the right conditions are to get the code to do what you want. When writing if statements, it can be a useful exercise to try and think through the variety of outcomes that might be possible when your code runs and determine how your if statements would be evaluated given these possible outcomes.
✅ Question 5.1 (3 Points)#
For each code snippet below, write the exact output you expect before you run it. Then run it and note whether your prediction was correct, and explain what the code is doing.
(a)
x = 12
if x > 0:
print("x is positive")
if x % 2 == 0:
print("x is even")
if x > 10:
print("x is greater than 10")
# Your predicted output (write here):
# Result and explanation after running (write here):
(b)
Note:
The operator in in Python checks whether something is contained inside something else.
For example:
3 in [1, 2, 3]will result inTrue4 in [1, 2, 3]will result inFalse
An if statement runs the code inside it only when the condition is True.
If the condition is False, the code inside that if block is skipped.
Documentation: Python Membership Tests
name = "sparty"
if name[0] in "aeiou":
print("starts with vowel")
else:
print("starts with consonant")
# Your predicted output (write here):
# Result and explanation after running (write here):
(c)
temp_c = 0
if temp_c < 0:
print("freezing")
elif temp_c < 20:
print("cool")
else:
print("warm")
# Your predicted output (write here):
# Result and explanation after running (write here):
✅ Question 5.2 (3 points)#
For each of the above examples from Question 5.1, do the following:
1) Test Inputs
Provide two different inputs (two different values for the variable) that lead to two different outputs.
Record both outputs and explain why they are different given those inputs.
2) Rewrite as a Problem
Write a short homework problem you could give to another CMSE 201 student, where the answer to your problem is the example code
✎ Respond to the questions for each example here.
Test Inputs (a):
Input 1:
Output 1:
Input 2:
Output 2:
Explanation:
Test Inputs (b) (note: only two possible outputs):
Input 1:
Output 1:
Input 2:
Output 2:
Explanation:
Test Inputs (c):
Input 1:
Output 1:
Input 2:
Output 2:
Explanation:
Rewrite as a Problem (a):
(your question here)
Rewrite as a Problem (b):
(your question here)
Rewrite as a Problem (c):
(your question here)
✅ Question 5.3 (3 points)#
Pick one of the following and implement it using if/elif/else.
Then show at least 3 test cases (inputs and outputs).
Option 1: Password Strength#
Write a program that checks a password string based on its first character:
If the first character is a digit (0-9), print
"starts with a number".If the first character is a special character like
!,@, or#, print"starts with a special symbol".Otherwise, print
"starts with a letter".
Test with "hello123", "!boom", and "9start".
Option 2: Movie Ticket Pricing#
Write a program that determines the ticket price based on a personâs age.
If they are under 5, print
"Free ticket".If they are between 5 and 17, print
"Child ticket: $8".If they are between 18 and 64, print
"Adult ticket: $12".If they are 65 or older, print
"Senior ticket: $7".
Test your program with at least 3 different ages to confirm it works, including one boundary case (like exactly 5, 17, 18, or 65).
For all of these problems, try to use good coding practices when writing your solutions!
In the markdown cell below, state which problem you intend to solve. Then, in the code cell below that, solve the problem using conditional statements.
✎ Write which of the 3 problems stated above you plan to solve here.
# Put your code that solves the problem, here.
# Make sure you make use of conditional statements
Wait! Before you submit your notebook, read the following important recommendations#
Look back at your work! Did you answer all of the questions to the best of your ability and cite any external resources?
When your TA opens your notebook to grade the assignment, it will be really useful if your notebook is saved in a fully executed state so that they can see the output of all your code. Additionally, it may be necessary from time to time for the TA to actually run your notebook, but when they run the notebook, it is important that you are certain that all the code will actually run for them!
You should get into the following habit: before you save and submit your final notebook for your assignments, go to the “Kernel” tab at the top of the notebook and select “Restart and Run all”. This will restart your notebook and try to run the code cell-by-cell from the top to the bottom. Once it finished, review you notebook and make sure there weren’t any errors that popped up. Sometimes, when working with notebooks, we accidentally change code in one cell that break our code in another cell. If your TA stumbles across code cells that don’t work, they will likely have to give you a zero for those portions of the notebook that don’t work. Testing your notebook one last time is a good way to make sure this doesn’t happen.
Once you’ve tested your whole notebook again, make sure you save it one last time before you upload it to D2L.
Congratulations, you’re done!#
Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Homework Assignments” section, find the submission folder link for Homework #1, and upload it there.
Copyright © 2025, Department of Computational Mathematics, Science and Engineering at Michigan State University, All rights reserved.