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.
This assignment is due at 11:59 pm on Friday, February 6th. 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 (10 points)
Storing and accessing data using lists (20 points)
Writing for loops in Python (30 points)
Writing while loops in Python (20 points)
Writing if statements in Python (20 points)
Total points possible: 110
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 and email to the CMSE 201 lead instructor, Dr. Rachel Frisbie (salmonra@msu.edu), to coordinate an option to make sure you can get credit for this part of the assignment.
NOTE: The day when the homework is due (Friday, February 6th) 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 and the calendar itself is embedded near the bottom of 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-s26-help channel on Teams!
1. Doing basic math with Python (10 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 (2 points)#
What is your major/minor/field of study?
✎ Put your answer here!
✅ Question 1.2 (2 points)#
From your major/minor/field of study, provide an example of where you use an arithmetic operator.
Example: I am an astronomy major, and we use exponentiation (i.e. **) in the equation for Luminosity of a star: \(L = 4 \pi R^2 \sigma T^4\)
Note: The example given is for an equation, but simple examples are also acceptable (e.g. I am a history major and I want to know how many decades it has been since World War II)
✎ Put your answer here!
✅ Question 1.3 (2 points)#
Describe how you came up with this example.
Example: First, I decided to choose exponentiation. Then, I remembered that in my intro class, we calculated lots of things with numers or variables to a power. I went back to my notes, and the first equation I flipped to that was easy to write in Markdown was the Luminosity equation, so that is what I picked.
✎ Put your answer here!
✅ Question 1.4 (2 points)#
Using your mathematics example, use code to demonstrate how you could use Python to perform the calculation.
### EXAMPLE ###
R = 6.96e8 #radius of sun in meters
sigma = 5.67e-8 # stefan-boltzmann constant in W/(m**2*K**4)
T = 5778 # temperature of sun in Kelvin
pi = 3.14
L = 4*pi*R**2*sigma*T**4
print(L)
3.845044120577153e+26
# put any code here
✅ Question 1.5 (2 points)#
Describe in detail how you created your example.
Example: I wanted Python to calculate a value for luminosity based on the variables and constants I had. I decided to use SI units because those were the units that Google gave me when I looked up the Stefan-Boltzmann constant. I chose the Sun because it was easy to find the luminosity and the temperature in the units I wanted. I decided it would make the code cleaner and help me keep track of units if I defined each variable and then combined them in the equation. Then I printed out the result. Then, I Googled the result I got and found out that it matched what it should have been, so my math should be correct.
✎ Put your answer here!
2. Storing and accessing data using lists (20 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.
2.1 List Creation and Manipulation (5 points)#
Create a list containing your first name, your age (as an integer), and your favorite food. Print that list.
Then, answer the questions below.
# Put your code here
2.1.1 Metacognition (5 points)#
What are the different data types you used for each item in your list?
Why did you choose to use those specific types for each piece of information?
✎ 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.
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.
2.2 List Indexing and Appending (5 points)#
Use list indexing to replace your age with the current year. Use the append() method to add a new item to the end of the list: your favorite color. Print the final, modified list.
# put your code here
2.2.1 Metacognition (5 points)#
Why is it important that you used indexing (e.g., my_list[1] = 2026) to change the value, instead of just creating a whole new list?”
What do you think would happen if you tried to access an index that doesn’t exist in the list, for example, my_list[5]?”
✎ Put your answer here!
3. Writing for loops in Python (20 points)#
The for loop is a fundamental programming concept in many programming languages and it is one method of what is referred to as “control flow,” which is simply how the flow of execution of a program is controlled (get it?). 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 sometimes refer to these as “looping by index” or “looping by value”, respectively.
Looping by integers or 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.
3.1 Writing a basic for loop by index (5 points)#
Write a for loop (using the range function) that runs for a number of iterations equal to the number of course credits you are taking this semester. For every iteration, the loop should print a sentence of your choice (e.g. “CMSE 201 is my favorite class this semester”). Then, answer the metacognition questions below.
Write your number of credits here for reference:
# put your code here
3.1.1 Metacognition (5 points)#
In the cell below, answer the following:
How did you determine the argument(s) for the range() function to ensure the loop ran for the correct number of iterations? What would happen if you used range(credits - 1) or range(credits + 1) instead?
If you wanted to print a different sentence for each iteration (e.g., “My first class is CMSE 201”, “My second class is MTH 132”), how would you modify your loop to achieve this? What Python concept would be most useful here?
✎ Put your answer here!
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.
3.2 Writing a basic for loop by value (5 points)#
Define a list that holds the names of the courses that you are taking as strings. Then write a for loop that loops by value over that list and prints out the name of each course. Then, answer the metacognition questions below.
# put your code here
3.2.1 Metacognition (5 points)#
This problem specifically asks you to loop “by value.” What is the difference between looping by value (e.g., for course in course_list:) and looping by index (e.g., for i in range(len(course_list)):)? In what situation might you choose one method over the other?
Imagine you also had a second list containing the number of credits for each course, in the same order. How would looping by value make it difficult to print both the course name and its corresponding credit number in the same loop? What approach would be better for that task?
✎ Put your answer here!
Writing a loop that accesses list values using integers or “by index”#
Now that you’ve looked at how you can use a for loop to move through a series of integer values and how you can use a for loop to step through a Python list of values, you’re go to explore how you can use the integer-based for loop approach to index values in a list inside a loops.
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 valuable.
3.3 Writing a basic for loop to access values in a list (5 points)#
From Part 3.2, you have a list of your courses. Create an additional list with the number of credits for each course as integers (make sure they are in the same order). Write a loop that iterates over the lists and prints a sentence stating the course and the corresponding number of credits. In addition, create a variable to add up the total amount of credits. Print the total after your loop. Then, answer the metacognition question below.
# put your code here
3.3.1 Metacognition (5 points)#
To print the course name and its corresponding credit value, you needed to access elements from two different lists at the same position in each loop iteration. Which looping method (looping by index or looping by value) did you choose to solve this, and why was that method the most effective choice for this specific task?
✎ Put your answer here!
4. Writing while loops in Python (25 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 ■ at the top of the notebook. You may also need to select “Restart Kernel and Clear Outputs of All Cells” from the “Kernel” menu.
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!
4.1 It’s a Pokemon Battle! (5 points)#
You need a program that will help you know when you should throw a Pokeball to catch a Pokemon. Fortunately, you just started in CMSE 201 and learned about while loops, so you’ve got this!
Write a while loop that starts with a maximum health number and decreases each iteration until it reaches one half of the maximum health number. You should print out the value of the health each time. When the loop condition is met, your program should print “Quick! Throw your Pokeball! The Pokemon’s health is:” and then the value of the Pokemon’s health. Make sure your loop stops before the Pokemon’s health reaches 0, otherwise it will faint and you can’t catch it!
Then, answer the metacognition questions below.
# put your code here
4.1.1 Metacognition (5 points)#
Why is a while loop a better choice for this problem than a for loop? What information do you have (or not have) that makes one loop structure more suitable than the other?
How did you decide on the condition to use in your while loop to make sure it stops at the right time?
Consider the placement of your print() statements. Why is it important where you place the statement that prints the health during the loop versus the statement that tells you to throw the Pokeball after the loop?
✎ Put your answer here!
4.2 The Zookeeper’s To Do List (10 points)#
Problem inspired by Dr. Frisbie’s 4 year old
Your preschooler told you that a zookeeper’s job is to “feed the animals and teach people about the animals.” You’ve decided to turn this into a programming game. You have a list of animals your preschooler likes and a list of tasks. Your goal is to create a “To-Do” list and then complete all the tasks.
Write a Python program that does the following:
Start with the two provided lists: animals and tasks.
Create a new empty list called
zookeeper_todo_list.Fill it up with to-do items using a loop and/or .append()
Print out your complete
zookeeper_todo_listto see what needs to be done.Now, write a
whileloop to “complete” the tasks. The loop should continue as long as there are items in thezookeeper_todo_listthat have not been changed to “done”. Inside thewhileloop:First, access the last item in the list using [-1] indexing and store it in a variable.
Print a message like: “Task completed: [task description]”, using the variable you just created.
Then, replace the completed item with the string “done”
Increment your counting variable by 1
After the loop finishes, print a final message: “All done! Here is the final checklist:” and print the modified
zookeeper_todo_list. Here are the lists to start with:
animals = [“Penguins”, “Otters”, “Goats”,”Arctic Fox”,”Eagles”,”Emus”,”Kangaroos”,”Bats”] tasks = [“Feed the”, “Teach people about the”]
# put your code here
4.2.1 Metacognition (5 points)#
In the while loop, you access an item using [-1] but then replace a different item using your counter variable. What would happen if you tried to replace the item at index [-1] in every iteration? How does using a separate counter change the way the program works?
This problem uses a while loop to modify the list. Could you achieve the same final checklist using a for loop instead? What challenges or advantages would you encounter if you tried to solve it that way?
✎ Put your answer here!
5. Writing “if” statements in Python (20 points)#
Conditional statements that are used outside of while loops in Python, often referred to as “if” statements, are a really useful way to control the flow of your code so that certain pieces of code are only executed when specific 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.
5.1 Creating your Pokemon Battle Team for the Six-Letter Tournament (10 points)#
You are a Pokemon trainer building your team for a tournament. You have a list of available Pokemon, but you only want to add Pokemon to your team if their name has 6 or more letters. You also have a rule that your team can only have a maximum of 6 Pokemon.
Write a Python program that does the following:
Start with the provided list of available_pokemon.
Create an empty list called battle_team.
Use a for loop to go through each Pokemon in the available_pokemon list.
Inside the loop, use an if statement to check two conditions:
Is the length of the Pokemon’s name 6 or more characters?
Is the number of Pokemon currently in your battle_team less than 6?
If both conditions are true, add the Pokemon to your battle_team list and print a message like: “Eevee has been added to your team!”
After the loop finishes, print a final message: “Your team selection is complete! Here is your team:” followed by the final battle_team list.
# put your code here
available_pokemon = ["Pikachu", "Teddiursa", "Rowlet", "Torchic", "Eevee", "Piplup",
"Empoleon", "Ariados", "Growlithe", "Ekans", "Arbok"]
5.1.1 Metacognition (5 points)#
Why is it important to check both the Pokemon’s name length and the current size of your battle_team inside the loop? What might happen if you only checked for the name length?
This problem was solved using a for loop. Could you have solved it with a while loop instead? What would need to change in your logic to make a while loop work, and which approach feels more natural for this specific task?
✎ Put your answer here!
5.2 Drawing a Troll (10 points)#
This problem inspired by the Hilda Graphic novel series by Luke Pearson
Background:
Hilda is a blue-haired girl that lives in the wilderness outside of Trolberg with her mother. She loves to explore the wilderrness and draw the things she sees. One day, she comes across a suspiciously shaped rock that turns out to be a troll rock! Fortunately for Hilda’s desire to draw everything she sees, trolls are frozen as rocks during the day and only come alive once the sun has set. Your task is to write a program that keeps track of the oncoming sunset to make sure the troll doesn’t wake up and chase Hilda!
You will need to write a program that does the following:
Initializes a variable to represent the sun level to a starting value (e.g.
sun_level = 100meaning full daylight)Initializes a variable to represent the a threshold of sun level that is low enough for the troll to wake up (e.g.
threshold = 10)Initializes a variable to represent a warning threshold of sun level that tells Hilda to get ready to leave (e.g.
warning = 30)Use a
whileloop to simulate the sun setting. The loop should continue as long as your sun level variable is greater than 0 (the sun hasn’t completely disappeared).Inside the while loop:
Print the current sun level.
Use
if/elif/elsestatements to provide different messages to Hilda:If the sun level is greater than the warning threshold, print a statement that tells Hilda she is safe to still be drawing.
Else if the sun level is greater than the threshold but not greater than the warning threshold, print a statement that warns Hilda it is time to clean up and get going
Else if the sun level is below the threshold, print a statement that tells Hilda to run away because the troll is waking up!
Each time through the loop, your sun level should decrease by a small amount
After the while loop finishes, print a final message indicating the end of the simulation.
Answer the metacognition questions below.
# put your code here
5.2.1 Metacognition (5 points)#
How did you determine the order of your if, elif, and else conditions? What would happen if you changed the order of these conditions, and why is the current order important for the program’s logic?
The problem uses a while loop to simulate the sun setting. Could you have achieved a similar outcome using a for loop with a range() function? What are the advantages or disadvantages of using a while loop versus a for loop for this specific simulation?
✎ Put your answer here!
Wait! Before you submit your notebook, read the following important recommendations#
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 © 2026, Department of Computational Mathematics, Science and Engineering at Michigan State University, All rights reserved.