Homework 1: Python fundamentals#
And using external resources to better undersand 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 loos of points on the problem.
This assignment is due at 11:59 pm on Friday, Jan 31. 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)
3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)]
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 (11 points)
Writing for loops in Python (21 points)
Writing while loops in Python (10 points)
Writing if statements in Python (9 points)
Total points possible: 71
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, Jan 31st) 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-SS25-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 (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 (2 Points)#
Provide an example of where you use an arithmetic operator in your major.
Example: I am a math major, and we use multiplication (i.e. *) in the equation for the area of triangle: \(A = \frac{1}{2}*b*h\)
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 (4 Points)#
Using your mathematics example, use code to demonstrate how you could use Python to perform the calculation.
### EXAMPLE ###
b = 1.75 #the lenght of the base
h = 3.87 # The height of the triangle
A = 1/2*b*h
print(A)
3.38625
# Put your answer here
2. Storing and accessing data using lists (11 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 animals, ensuring that the first animal in your list is a dog. 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 animal list created in Question 2.1.
Using your knowledge from CMSE 201, write code that changes the first animal, dog, to tiger. 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 (4 Points)#
Now you’re going to write a bit of code that uses the append()
function to add items to a Python list.
Write code to create a list containing the first names of all your group members in CMSE201. Then, using the append() function, add the first names of your instructor and TA to the list. Print the list to ensure the results are as expected.
#Put your answer here
3. Writing for
loops in Python (21 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.
✅ Question 3.1 (2 Points)#
Using the internet, find some examples of how the range()
function can be used to generate integer values inside a for
loop. After you find some examples, pick two of the examples, copy them into your notebook in the code cells below, and get them to run. Since you’re using code you found on the internet, include a comment in your code (using the #
symbol) that provides the URL that your example came from and the date you accessed that URL. Your comment should look something like:
# Original code from https://superusefulpythoncode.com/for-loops-are-great/, accessed on January 17, 2025
# Put your first example, where it came from, and when you accessed the URL here
# Put your second example, where it came from, and when you accessed the URL here
✅ Question 3.2 (2 Points)#
For each example, answer the following questions in the markdown cell below.
What does this example do?
Considering what the example code you found and copied does, write a homework problem you could give another CMSE 201 student, where the answer to your problem is the example code you’ve found.
For example, if my code example was:
for i in range(3): print(i)
then my prompt might be “Write a program using a for loop that prints the number 0, 1, 2, in order one number at a time”
✎ Respond to the questions for each example here.
✅ Question 3.3 (3 Points)#
Now that you’ve looked at some examples that use the range()
function in a for
loop iterate over a set of integers, you’re going to write a bit of code that includes a for
loop that uses the range()
function.
Write a program that produces the “compound interest” for a given starting principal using some interest rate over n years, where n is an integer value. For example, if you were to choose 9 as your integer, 0.05 as your rate, and 1000 as your principal, your program should print something like:
```
> Year Amount on deposit
> 0 1000
> 1 1050
> 2 1102.50
> ... (all of the other ones)
> 9 1551.3282159785163
> ```
hint: The principal plus the compound interst at any year yr
is computed according to principal * (1 + rate)**yr
** Do your best to use good coding practices when writing your solutions!**
# Put your code that solves the problem, here.
# Make sure you make use of a for loop and the range function
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.
✅ Question 3.4 (2 Points)#
Using the internet, find some examples where a for
loop is used to move through a Python list and the code does something with the values in that list. After you find some examples, pick two of the examples, copy them into your notebook in the code cells below, and get them to run. Since you’re using code you found on the internet, include a comment in your code (using the #
symbol) that provides the URL that your example came from and the date you accessed that URL. Your comment should look something like:
# Original code from https://superusefulpythoncode.com/for-loops-are-great-with-lists-too/, accessed on January 19, 2025
# Put your first example, where it came from, and when you accessed the URL here
# Put your second example, where it came from, and when you accessed the URL here
✅ Question 3.5 (2 Points)#
For each example, answer the following questions in the markdown cell below.
What does this example do?
As before, considering what the example code you found and copied does, write a homework problem you could give another CMSE 201 student, where the answer to your problem is the example code you’ve found.
✎ Respond to the questions for each example here.
✅ Question 3.6 (3 Points)#
Now that you’ve looked at some examples that use a for
loop to iterate through a list, you’re going to write a bit of code that uses a for
loop to iterate through a list
Crack the code: You are given a mysterious list of entries in the code chunk below. The Peak Heights Detectives’ Agency approached you asking for your help in cracking the code. You suspect that the frequency of ‘f’ and ‘i’ in each entry is significant, and you come up with a plan.
You’re going to loop by value to iterate through this list and output the number of ‘f’s and the number of ‘i’s side by side. Examine the result, and make a guess on what these values might represent (does not matter if you guess wrong, just make an educated guess!).
Use the built-in Python count
function to count the ‘f’s and ‘i’s in each entry. The count
function will give you the number of things you are looking for found in a particular variable. For example, if you want to know how many ‘t’s there are in a variable called entry
that holds the string ‘Ethylenediaminetetraacetates’ we would write a code like this:
entry = 'Ethylenediaminetetraacetates'
number_of_ts = entry.count('t') # note the format of: variable name followed by a ., followed by count, with the value 't' that you are looking for!
print(number_of_ts)
An example output will look like this:
```
> Entry Number of 'f's Number of 'i's
> fffffiiiii 5 5
> ... (all of the other ones)
```
For all of these problems, do your best to use good coding practices when writing your solutions (see Day 4 In Class for a reminder)!
# Put your code that solves the problem, here.
# Make sure you make use of a for loop that iterates through a list
# do not change the mysterious_list--------------------------------------------------------------------
mysterious_list = ['fffffiiiii', 'fffffiiiii', 'ffffffiiiiiiiii', 'ffffffiiiiii', 'ffffffiiiiiii',
'ffffffiiiiiii', 'fffffiiii', 'ffffffiiiiiii', 'fffffiiii', 'fffffiiii']
# do not change the mysterious_list--------------------------------------------------------------------
# start your answer here.
✎ What do think these entries are encoding? Justify your answer.
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 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.7 (2 Points)#
Using the internet, find some examples where a for
loop uses the range()
function to generate integers that are then used as indices (the plural of “index”) to access information from a list inside the loop. After you find some examples, pick two of the examples, copy them into your notebook in the code cells below, and get them to run. Since you’re using code you found on the internet, include a comment in your code (using the #
symbol) that provides the URL that your example came from and the date you accessed that URL. Your comment should look something like:
# Original code from https://superusefulpythoncode.com/for-loops-with-range-can-access-lists/, accessed on January 20, 2025
# Put your first example, where it came from, and when you accessed the URL here
# Put your second example, where it came from, and when you accessed the URL here
✅ Question 3.8 (2 Points)#
For each example, answer the following questions in the markdown cell below.
What does this example do?
As before, considering what the example code you found and copied does, write a homework problem you could give another CMSE 201 student, where the answer to your problem is the example code you’ve found.
✎ Respond to the questions for each example here.
✅ Question 3.9 (3 Points)#
Now that you’ve looked at some examples that use the range()
function in a for
loop to access information in list, you’re going to write a bit of code that does precisely this.
The example we will use your coding prowess to calculate the weights of eggs sorted according to their weight. The Egg Size Table shows that eggs can be categorized as follows based on their weight:
Jumbo:Carton weight: 30oz. Egg weight: 2.5oz.
Extra large: Carton weight: 27oz.Egg weight: 2.25oz.
Large: Carton weight: 24oz. Egg weight: 2oz.
Medium: Carton weight: 21oz. Egg weight: 1.75oz.
Small: Carton weight: 18oz. Egg weight: 1.5oz.
Peewee: Carton weight: 15oz. Egg weight: 1.25oz.
The manufacturer recorded the weights of individual eggs in each type of carton, and your job is to loop through and tally the total weight for each kind of given carton. Write your code in the code chunk below. Note that the two lists have the same length, and that the entries correspond to each other. For example, the first entry in eggs_per_carton contains the weights of the dozen eggs in the Jumbo carton, etc.
An example output for a jubmo dozen with eggs of identical weight 2.5 oz will look like this (note that 12 x 2.5 = 30):
```
> Type Total weight (oz)
> Jumbo 30
> ... (all of the other ones)
```
_hint_: You can sume the entries of a list using the sum() method. For example, sum([0,1,2,3,4])=10
For all of these problems, do your best to use good coding practices when writing your solutions!
# Put your code that solves the problem, here.
# Make sure you make use of a for loop and the range function to access information is one or more lists
# Do not change this---------------------------------------------------------------
cartons_list = ['Jumbo', 'Extra_large', 'Large', 'Medium', 'Small', 'Peewee'] # six types
# each entry contains the weights of a dozen eggs corresponding to each of the types above
dozen_of_each_type = [[2.63, 2.61, 2.72, 2.52, 2.66, 2.72, 2.65, 2.58, 2.68, 2.53],
[2.39, 2.34, 2.3, 2.2, 2.39, 2.35, 2.38, 2.36, 2.21, 2.31],
[2.12, 2.03, 2.34, 2.39, 2.05, 2.09, 2.23, 2.27, 2.09, 2.32],
[1.76, 1.86, 1.81, 1.86, 1.81, 1.84, 1.83, 1.8, 1.77, 1.86],
[1.67, 1.65, 1.64, 1.64, 1.52, 1.71, 1.57, 1.57, 1.58, 1.61],
[1.38, 1.33, 1.41, 1.32, 1.47, 1.27, 1.31, 1.35, 1.28, 1.4]]
# Do not change the above---------------------------------------------------------
# write your answer here
4. Writing while
loops in Python (10 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.
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 (2 Points)#
Using the internet, find some examples of how a while
loop can be used to repeatedly execute a block of code until a specific condition is met. After you find some examples, pick two of the examples, copy them into your notebook in the code cells below, and get them to run. Since you’re using code you found on the internet, include a comment in your code (using the #
symbol) that provides the URL that your example came from and the date you accessed that URL. Your comment should look something like:
# Original code from https://superusefulpythoncode.com/while-loops-can-be-handy-but-dangerous/, accessed on January 18, 2025
# Put your first example, where it came from, and when you accessed the URL here
# Put your second example, where it came from, and when you accessed the URL here
✅ Question 4.2 (2 Points)#
For each example, answer the following questions in the markdown cell below.
What does this example do?
Considering what the example code you found and copied does, write a homework problem you could give another CMSE 201 student, where the answer to your problem is the example code you’ve found.
For example, if my code example was:
i = 0 while i < 3: print(i) i = i + 1
then my prompt might be “Write a program using a while loop that prints all integers that are less than 3, starting with 0.”
✎ Respond to the questions for each example here.
✅ Question 4.3 (3 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.
First, you will create an infinite loop. You read that correctly, we will attempt to make a while loop go on forever, and see what happens. Write 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!).
# Write your infinite loop here
✎ What do you get when you run this program? Write your answer here.
✅ Question 4.4 (3 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 will use a while loop to approximate a series (a mathematical expression that adds infinitely many terms). The series we will work with is given by $\(\sum\limits_{n=1}^{\infty}{\frac{1}{2^n}}=\frac{1}{2} + \frac{1}{4}+\frac{1}{8}+\frac{1}{16}+\ldots\)$
This series is guaranteed to theoretically converge, i.e., as we keep adding more and more terms they will tend to a specific value. In this question, the given series will get closer and closer to 1, i.e., it converges to 1.
Computationally, we will cannot sum an infinite series, but we can tell the computer to keep summing a series until the difference between two consecutive partial sums is below a certain threshold. For example, consider the two consecutive partial sums
$\(s_1 = \sum\limits_{n=1}^{3}{\frac{1}{2^n}}=\frac{1}{2} + \frac{1}{4}+\frac{1}{8} \text{; and } s_2 = \sum\limits_{n=1}^{4}{\frac{1}{2^n}}=\frac{1}{2} + \frac{1}{4}+\frac{1}{8}+\frac{1}{16}\)\(
The difference between these two consecutive sums is \)e=|s_2-s_1|$, where the overbars indicate the absolute value function which can be coded in python using the abs()
method.
Write a while loop that obtains the partial sum of the given infinite series until the difference between consecutive partial sums is less than 0.01. Print the partial sum \(s_2\) and the error \(e=|s_2 - s_1|\) at each iteration in the while loop. Your output must look like this
```
> s2 error
> 0.5 0.5
> 0.75 0.25
> 0.875 0.125
> ... (all of the other ones)
```
For all of these problems, Do your best to use good coding practices when writing your solutions!
hint: The partial sum will quickly converge in less than 10 steps. If it’s taking longer, interrupt the kernel and debug your code.
## Write your answer here
5. Writing “if
” statements in Python (9 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.
✅ Question 5.1 (3 Points)#
Using the internet, find some examples of how if
statements, if
-else
statements, and if
-elif
-else
statements can be used in Python to control the flow of your code. After you find some examples, pick three of the examples such that you have:
One example that uses just one or more
if
statementsOne example that uses the combination of
if
andelse
One example that uses the combination of
if
,elif
, andelse
Copy these examples into your notebook in the code cells below, and get them to run.** Since you’re using code you found on the internet, include a comment in your code (using the #
symbol) that provides the URL that your example came from and the date you accessed that URL. Your comment should look something like:
# Original code from https://superusefulpythoncode.com/conditional-statements-are-cool/, accessed on January 22, 2025
# Put your first example, where it came from, and when you accessed the URL here
# Put your second example, where it came from, and when you accessed the URL here
# Put your third example, where it came from, and when you accessed the URL here
✅ Question 5.2 (3 Points)#
For each example, answer the following questions in the markdown cell below.
What does this example do?
Considering what the example code you found and copied does, write a homework problem you could give another CMSE 201 student, where the answer to your problem is the example code you’ve found.
✎ Respond to the questions for each example here.
✅ Question 5.3 (3 Points)#
Now that you’ve looked at some examples that use if
statements (or more complex statements with elif
and else
) to control the flow of your code based on specific conditions, you’re going to write a bit of code that uses conditional statements.
Since there a wide variety of problems that can be tackled with this sort of code, you have the option to choose from one of the following problems:
Write a program that determines if a word (as a string) ends with the letter
'e'
,'s'
, or something else. If the word ends with the letter'e'
, print “ends with e”, if the word ends with the letter's'
, print “ends with s”, and if the word doesn’t end with an'e'
or's'
, print “does not end with e or s.” Test your program with the words'apple'
,'rabbits'
, and'lynx'
, to confirm your program works.Write a program that determines if a given number is even or odd. Test your code with at least 4 example numbers to ensure your program works.
Write a program that determines if a student got an “A”, “B”, “C”, or did worse in a course, based on a numerical score with a maximum of 100. If a student scored better than 90, print “You got an A”. If they scored between 80 and 90, print “You got a B”. If they scored between 80 and 90, print “You got a C”. If they scored less than 70, print “You need to study more!”.
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.