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.
Use functions to organize code and make it more readable and reusable.
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, September 27. 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#
Doing basic math with Python (6 points)
Storing and accessing data using lists (21 points)
Writing for loops in Python (21 points)
Writing while loops in Python (7 points)
Writing if statements in Python (9 points)
Writing functions in Python (11 points)
Putting it all together (15 points)
Total points possible: 90
1. Doing basic math with Python (6 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)#
One arithmetic operator is missing from the table above. This is the “Floor Division” operator, which looks like this: //
In your own words in the cell below, explain what this operator does. In the code cell below that, use the operator in an example to confirm that your explanation is accurate.
✎ Put your explanation here.
# Put your example code that showcases how the // operator works to ensure that it agrees with your explanation
2. Storing and accessing data using lists (21 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 has been 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 (2 Points)#
Using the internet, find some examples of how the create a list in Python. 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. Try to find two examples that are different in some way, e.g. the examples create the list in different ways or store different types of values.
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/lists-are-handy/, accessed on August 21, 2024
Tip: You’ll be asked to use the internet to find various types of example code throughout this assignment. Remember, when you’re searching for example, it can be very important to include “python” in your search terms to make sure you get code that’s written in Python, rather than some other language.
Note: Feel free to experiment with using Generative AI (e.g. ChatGPT, Claude, etc.) or the course AI assistant (HiTA) to generate code examples. Just make sure you’re indicate what tool you used to generate the example and leave a comment as described above.
# 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 2.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 prompt you could give another CMSE 801 student, where the answer to your problem is the example code you’ve found.
For example, if my code example was:
mylist = [0, 1, 2] print(mylist)
then my prompt might be “Write a program that creates a list that contains the integer numbers 0, 1, and 2 and then prints the list”
✎ Respond to the questions for each example here.
✅ Question 2.3 (3 Points)#
Now that you’ve looked at some examples that create a Python list, you’re going to write a bit of code that creates such a list.
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 creates a list containing the months of the year in order, starting with January. Print the list to ensure it includes all twelve months.
Create a Python program that generates a list of the first 10 multiples of a given number (e.g., 5, 10, 15, …). Ensure that these multiples are stored as integers, and print the list to verify the values.
Write a program that generates a list containing the first 10 consonants in the English alphabet in lowercase. Make sure to exclude vowels and any other non-alphabet characters. Print the list to confirm that it contains all the appropriate consonants.
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 by creating a Python list and using it as indicated.
✎ 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 a list
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.4 (2 Points)#
Using the internet, find some examples of how the access values and change values in a list in Python using an index. After you find some examples, pick:
one example that just accesses values in a list using an index, and
one example that shows how you can use an index to change a value in a list.
Copy each example into your notebook in the code cell below and get them both 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/lists-can-be-accessed-and-changed/, accessed on August 25, 2024
# 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 2.5 (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 prompt you could give another CMSE 801 student, where the answer to your problem is the example code you’ve found.
✎ Respond to the questions for each example here.
✅ Question 2.6 (3 Points)#
Now that you’ve looked at some examples that create a Python list, you’re going to write a bit of code that accesses and changes values in a list.
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 creates a list of odd natural numbers that are less than 10. Then change the second number so that it is the original value squared, change the fifth number so that it increases by 3 from the original value. Print the list to make sure the results are what you expect.
Write a program that creates a list that contains individual letters in the word “python” all in lower case. Then change the first letter to uppercase, and the letter “o” to the integer 0. Print the list to make sure the results are what you expect.
Write a program that creates a list that contains the names of the four inner planets of the solar system. Then change the name of the one that we live on to be “home world”. Print the list to make sure the results are what you expect.
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 by accessing and modifying values in a list.
✎ 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 a list to access and modify the values
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.7 (2 Points)#
Using the internet, find some examples of how to append values to a list in Python. 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/lists-can-appended-to/, accessed on August 27, 2024
# 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 2.8 (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 801 student, where the answer to your problem is the example code you’ve found.
✎ Respond to the questions for each example here.
✅ Question 2.9 (3 Points)#
Now that you’ve looked at some examples that append items to a Python list, you’re going to write a bit of code that uses the append() function to add items to a Python list.
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 creates a list that contains all of the vowels in the alphabet. Then using the
append()function, add the first letter of your first name and the first letter of your last name to the end of the list. Print the list to make sure the results are what you expect.Write a program that creates a list that contains the days of the week in order. Then using the
append()function, add your favorite day of the week and your busiest day of the week to the end of the list. Print the list to make sure the results are what you expect.Write a program that creates a list that contains the first 10 natural numbers. Then using the
append()function, add your favorite number and the day of the month you were born (e.g. if you were born February 29th, you would add29) to the end of the list. Print the list to make sure the results are what you expect.
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 by appending new values to a list.
✎ 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 a list to access and modify the values
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 August 28, 2024
# 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 prompt you could give another CMSE 801 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.
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 produces the “multiplication table” for a given integer value for that integer times 0 through 10. For example, if you were to choose “9” as your integer, your program should print something like:
9 times 0 is 0 9 times 1 is 9 9 times 2 is 18 ... (all of the other ones) 9 times 10 is 90
Write a program that calculates the sum of the first “n” integers (starting with zero) where “n” is a number of your choosing. Once the sum is calculated, print the result. For example, if you were to choose “3” as your value of “n” your code should calculate 0 + 1 + 2 and print the sum at the end (which would be 3 in this case).
Write a program that starts at zero and goes to some number “n” and prints out all of the odd integers in that range, where “n” is a value of your choosing. For example, if you chose “6” as your value of “n” then your code should print 1, 3, and 5. Hint: if you choose this one, you might find it useful to use the “modulo” operator you should have learned about when you completed Part 1 of this assignment.
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 a for loop that uses the range() function.
✎ 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 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 CMSE 801, 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 September 1, 2024
# 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 prompt you could give another CMSE 801 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
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 takes the following list, iterates through it using a
forloop without using index values to access the items in the list, and prints the first letter of each item in the list. The list you should use is:['Nine','iguanas','consumed','eight','Wooly','orange','riggly','katerpillars'] # hmm... a couple words are spelled strangely...
Write a program that takes the following list, interates through it using a
forloop without using index values to access the items in the list, and prints the result of each number in the list times 9. The list you should use is:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Write a program that takes the following list, iterates through it using a
forloop without using index values to access the items in the list, and prints the length of each item in the list. The list you should use is:['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
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 a for loop that iterates through a list.
✎ 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 a for loop that iterates through a list
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 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 September 2, 2024
# 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 prompt you could give another CMSE 801 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.
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 iterates through two lists (which are the same length) and prints the product of the values in the lists such that the result of the first iteration is the first item in the first list multiplied by the first item in the second list, the result of the second iteration is the second item in the first list multiplied by the second item in the second list, and so on…
Use these two lists:
[0, 1, 2, 3, 4, 5, 6] [10, 11, 12, 13, 14, 15, 16]
Write a program that iterates through two lists (which are the same length), concatenates the letters in each list item-by-item, and prints the concatenated results for each iteration. The end result should be such that the printed output of the first iteration is the concatenation of the first item in the first list with the first item in the second list, the second printed output is the concatenation of the second item in the first list with the second item in the second list, and so on…
Use these two lists:
['H', 'the', 'gre', 'wo', 's', 'f'] ['i', 're', 'at', 'rk', 'o', 'ar']
As a reminder, you can concatenate two strings by using the
+operator in Python.Write a program that iterates through two lists (which are the same length), takes the length of the item in the first list and divides it by the value in the second list, and prints the result for each iteration. The end result should be printed output of numbers such that the first output is the length of the first item in the first list divided by the first value in the second list, the second output is the length of the second item in the first list divided by the second value in the second list, and so on…
Use these two lists:
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
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 the range() function in for loop that accesses information from one or more lists.
✎ 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 a for loop and the range function to access information is one or more lists
4. Writing while loops in Python (7 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 September 4, 2024
# 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 prompt you could give another CMSE 801 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.
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 prints all of the integers (starting at 0) that are less than some number “n” where “n” is a number of your choosing. Make sure you don’t accidentally create an infinite loop!
Write a program that calculates a running sum of all odd numbers (starting with 1) until the sum is greater than 56. Print out the sum after each number you add to the total. To clarify this a bit, you should add 1+3, which is 4, then 4+5, which is 9, then 9+7, which is 16, and so on… The loop should stop after the sum becomes greater than 56. Make sure you don’t accidentally create an infinite loop!
Write a program that keeps track of how many tacos are consumed assuming that people greedily eat 5 tacos at a time and stops running when there are no longer 5 or more tacos left to eat. Assume that you start with 42 tacos. Print how many tacos are left in each iteration of your loop. Make sure you don’t accidentally create an infinite loop!
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 a while loop.
✎ 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 a while loop
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
ifstatementsOne example that uses the combination of
ifandelseOne 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 September 5, 2024
# 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 prompt you could give another CMSE 801 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
'a','b', or something else. If the word ends with the letter'a', print “ends with a”, if the word ends with the letter'b', print “ends with b”, and if the word doesn’t end with an'a'or'b', print “does not end with a or b.” Test your program with the words'superb','banana', and'potato', to confirm your program works.Write a program that adds 2 to a number if it is less than 10, multiplies the number by 3 if it is greater than 10, and mutiplies the number by 4 if it is 10. Print out the result at the end. Make sure to test your code for all three cases to ensure your program works.
Write a program that compares two digital numbers a and b. If b is greater than a, print “b is greater than a”. If b is not greater than a, then print “b is not greater than a.”
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
6. Writing functions in Python (11 points)#
As we start building more and more complex code, you might find yourself using the “copy-paste” functionality a lot to reuse certain snippets of code that perform a useful task. When you find yourself using the same chunk of code over and over again, it might be time to think about turning that code into a function!
Remember, functions are a great programming concept because they are:
Modular
Re-usable
Useful
While functions can help us to build progressively more sophisticated code, we need to make sure we understand the basic structure of a function to properly write them.
✅ Question 6.1 (4 points)#
Using the internet, find some examples of how functions can be written and used in Python. After you find some examples, pick four of the examples such that you have:
One example that does not require any input arguments and doesn’t use the
returnstatement.One example that does use the
returnstatementOne example that uses does use input arguments (i.e. there should be variables between the
()in the function definition).One example that uses input arguments that have default values.
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/functions-are-powerful/, accessed on September 6, 2024
# 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
# Put your fourth example, where it came from, and when you accessed the URL here
✅ Question 6.2 (4 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 prompt you could give another CMSE 801 student, where the answer to your problem is the example code you’ve found.
✎ Respond to the questions for each example here.
✅ Question 6.3 (3 points)#
Now that you’ve looked at some examples of functions that can be written in Python, you’re going to write some Python functions from scratch.
Since there are 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 function that takes a list of strings as an input and concatenates the strings from the list into one long string where each string in the list is separated by a space (i.e.
' '). Store that concatenated string in a new variable inside the function called “sentence” and return that variable. Make sure to write some code that tests your function to ensure that it is working.Write a function that takes in three separate numbers as arguments, prints the largest number, and returns the smallest number. Make sure to write some code that tests your function to ensure that it is working.
Write a function that takes two arguments of any type and compares them to each other. Use
v1for the first argument andv2for the second argument. If the arguments are identical, it should print “These are the same.” If the arguments are different, it should print “These are not the same.” Set the default value for the first argument to be"801” (a string) and set the default value for the second argument to be801(an integer). Make sure to write some code that tests your function to ensure that it is working.
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 by writing and using a function.
✎ Write which of the 3 problems stated above you plan to solve here.
# Put your code that solves the problem, here.
# Make sure you create and test a function.
7. Putting it all together: student grade analysis (15 points)#
Now that you’ve had a chance to explore a variety of Python programming concepts, you’re going to put all of these concepts together to solve a problem that will require using most, if not all, of the concepts you’ve covered in this assignment.
In the cell below, you are provided with a list of student names and a list of their corresponding grades on a recent exam. In order to analyze the students’ exam performance, your job is to do the following:
Write a function called
calculate_averagethat takes a list of grades as an argument and returns the average of those grades.Write a function called
find_highest_gradethat takes a list of grades as an argument and returns the highest grade in that list.Write a function called
find_lowest_gradethat takes a list of grades as an argument and returns the lowest grade in that list.Write a function called
grade_summarythat takes a list of student names and a list of grades as arguments and prints each student’s name along with their grade, and then also prints the average, highest, and lowest grades for the class. Make sure to use the functions you wrote in steps 1-3 to calculate the average, highest, and lowest grades.Use a loop to iterate through the list of grades to count how many students passed the exam. Consider a passing grade to be 60 or above.
Within in the loop, use an
ifstatement to determine if a student passed the exam and increment a counter variable if they did.
Your code should display all of the following information when it is run:
Each student’s name and grade (this should be coming from your
grade_summaryfunction)The average grade for the class (this should be coming from your
calculate_averagefunction, which should be called within yourgrade_summaryfunction)The highest grade in the class (this should be coming from your
find_highest_gradefunction, which should be called within yourgrade_summaryfunction)The lowest grade in the class (this should be coming from your
find_lowest_gradefunction, which should be called within yourgrade_summaryfunction)The number of students who passed the exam (this should be calculated using a loop and an
ifstatement with the result being printed at the end of your code)
You output should look something like this:
Student grades: Alice: 85 Bob: 70 Charlie: 60 David: 55 Emily: 90 Frank: 75 Grace: 65 Henry: 80 Isabel: 95 Jack: 50 Average Grade: 72.5 Highest Grade: 95 Lowest Grade: 50 Number of students who passed: 8
Hints: you’ll likely find the len(), sum(), min(), and max() functions useful when writing your functions.
## DO NOT MODIFY THIS CELL.
## PUT YOUR CODE IN THE CELL BELOW
# List of student names
students = ['Alice', 'Bob', 'Charlie', 'David', 'Emily', 'Frank', 'Grace', 'Henry', 'Isabel', 'Jack']
# List of exam scores
grades = [85, 70, 60, 55, 90, 75, 65, 80, 95, 50]
# Put your code 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 © 2024, Department of Computational Mathematics, Science and Engineering at Michigan State University, All rights reserved.