Homework 1: Python fundamentals

Contents

Homework 1: Python fundamentals#

And using external resources to better understand code!#

Put your name here

#

CMSE Logo

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, September 20th. 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#

  1. Integrity statement and office hours

    1. Academic Integrity Statement (2 points)

    2. Going to Office Hours (8 Points)

  2. Doing basic math with Python (18 points)

  3. Storing and accessing data using lists (20 points)

  4. Writing for loops in Python (21 points)

  5. Writing while loops in Python (14 points)

  6. Writing if statements in Python (17 points)

Total points possible: 100


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. Your statement needs to be personalized to receive full credit for this item.

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, September 20th) 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 as well as the Zoom information. 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-F24-help channel on Teams!


1. Doing basic math with Python (18 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 (4 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 (4 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 (4 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 your answer here!

✅  Question 1.5 (4 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.

✅  Question 2.1 Creating a List (4 points)#

Using your in class group members’ first names as items in the list. Demonstrate two different ways that you could create a list with those elements. Print out your list!

# Put your answer here!

✅  Question 2.2 Describe your thought process (4 points)#

In the cell below, provide an explanation for how you identified two different ways to construct the lists and how you created the code.

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.3 (3 Points)#

Now that you’ve identified different ways to make lists, you’re going to write a bit of code that accesses and changes values in a list.

Using your knowledge from CMSE 201, write some code that creates a list containing 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.

Try to use good coding practices when writing your solutions! (See Day 4 for guidance on PEP8 formatting)

# Put your answer here

✅  Question 2.4 Describe your problem solving technique (3 points)#

In the cell below, provide a detailed explanation for how you solved this problem

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.5 (3 Points)#

Now you’re going to write a bit of code that uses the append() function to add items to a Python list.

Write some code that creates a list that contains the names of all the planets of the solar system. Then using the append() function, add the names of two additional, fictional planets (e.g. Tatooine). Print the list to make sure the results are what you expect.

Try to use good coding practices when writing your solutions! (See Day 4 for guidance on PEP8 formatting)

# Put your answer here!

✅  Question 2.6 Describe your problem solving technique (3 points)#

In the cell below, provide a detailed explanation for how you solved this problem.

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, 2023
# 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.

  1. What does this example do?

  2. 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.

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:

  1. Write a program that converts Temperature in degrees Fahrenheit to degrees Celsius. The program should print out a table of Fahrenheit temperatures (starting at 25 and going to 35) and the corresponding Celsius temperatures. The formula for converting Fahrenheit to Celsius is: \(C = (F - 32) \times \frac{5}{9}\). Your output should look something like:

    25 degrees Fahrenheit is -3.89 degrees Celsius
    26 degrees Fahrenheit is -3.33 degrees Celsius
    27 degrees Fahrenheit is -2.78 degrees Celsius
    ... etc.
  1. Write a program that calculates the factorial (\(x!\) where \(x\) is an integer). In a factorial, all the preceeding integers are multipled together to compute the factorial. For example, \(5! = 5 \times 4 \times 3 \times 2 \times 1 = 120\). Your program should print each step of the calculation with the final number being the answer. Make sure that \(x\) is not too large; brute force factorial calculations can quickly exceed memory limits. Your output should look something like:

    5
    10
    30
    120
  1. 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 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, 2023
# 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.

  1. What does this example do?

  2. 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.

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:

  1. Write a program that takes the following list, iterates through it using a for loop 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:

    ["Clever", "Radiant", "Unforgettable", "Stunning", "Heroic", "Incredible", "Noble", "Great", "Inspiring", "Tireless"]
    
  2. Write a program that takes the following list of Fahrenheit temperatures, iterates through it using a for loop without using index values to access the items in the list, and converts each to a temperature in celsius using the formula \(C = (F - 32) \times \frac{5}{9}\). The list you should use is:

    [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
  3. Write a program that takes the following list, iterates through it using a for loop 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:

    ['Lion', 'Octopus', 'Kangaroo', 'Penguin', 'Koala', 'Crocodile', 'Chimpanzee', 'Fox', 'Rattlesnake', 'Wolf']
    

    Note: Look back on the Day 2 Pre-class Assignment for getting a single value in a string if you’re having trouble!

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 going 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.

✅  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, 2023
# 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.

  1. What does this example do?

  2. 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.

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:

  1. Write a program that iterates through two lists (which are the same length) and prints the result of dividing the values in the lists such that the result of the first iteration is the first item in the first list divided by the first item in the second list, the result of the second iteration is the second item in the first list divided by the second item in the second list, and so on…

Be careful with the order of the lists! You cannot divide by zero.

Use these two lists:

[0, 1, 2, 3, 4, 5, 6]
[10, 11, 12, 13, 14, 15, 16]
  1. 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:

['He', 'yo', 'a', 'doi', 'gr', 'ke', 'i', 'u']
['y', 'u', 're', 'ng', 'eat', 'ep', 't', 'p']
**As a reminder**, you can concatenate two strings by using the `+` operator in Python.
  1. Write a program that iterates through two lists (which are the same length), takes the length of the item in the first list and adds 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 added to the first value in the second list, the second output is the length of the second item in the first list added to the second value in the second list, and so on…

Use these two lists:

['Lion', 'Octopus', 'Kangaroo', 'Penguin', 'Koala', 'Crocodile', 'Chimpanzee', 'Fox', 'Rattlesnake', 'Wolf']
[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 (14 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 (4 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, 2023
# 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 (4 Points)#

For each example, answer the following questions in the markdown cell below.

  1. What does this example do?

  2. 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 (6 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 is 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:

  1. Write a program that prints the sum of all the odd numbers (starting at 1) 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!

  2. Write a program that calculates the number of months someone has been alive each year up until their 900th month of life. That is, the first time through the loop, the number of total months is 12, the second time through the loop, the number of total months is 24, the third time through the loop, the total number of months is 36, and so on up to 900. The loop should stop after the number of months exceeds 900. Make sure you don’t accidentally create an infinite loop!

  3. Write a program that keeps track of how many tacos are consumed assuming that people eat a very reasonable number of tacos at a time - 3 tacos is quite reasonable - and stops running when there are no longer 3 or more tacos left to eat. Assume that you start with a 74 tacos - again a very reasonable amount. 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 (17 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 even more 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)#

Searching the web to debug/troubleshoot error messages.

The following three code chunks when attempted to be run will produce an error. Your job is to run each cell, read the error message, and copy the text from the error. Once copied, go to a search engine, paste the error text, and search for online results. Click on one of the results or as many as needed until you can find and fix the error, but you must at least visit one site.

Not every site from a search result is going to be helpful. It may take looking through multiple sites to understand the error. If after looking through 5 websites, you cannot determine the error and fix the code, take a look at this resource for guidance: https://www.w3schools.com/python/python_conditions.asp

After you fix the code, include a comment in your code that provides the URL of the site where you found your answer/fix, the date you accessed that URL, and how many sites you had to visit before finding an answer/fix. Your comment should look something like:

# Answer from https://superusefulpythoncode.com/conditional-statements-are-cool/, accessed on January 22, 2023, number of attempts was 1
x = 5

if x = 5:
    print('x equals 5')
else:
    print('x does not equal 5')
    
# Write your comment of how many sites you visited
  Cell In[136], line 3
    if x = 5:
       ^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
y = 10

if y == 10
    print('y equals 10')
else
    print('y does not equal 10')
    
# Write your comment of how many sites you visited
  Cell In[138], line 3
    if y == 10
              ^
SyntaxError: expected ':'
z = 0

if z == 0:
print('z equals 0')
else:
print('z does not equal 0')

# Write your comment of how many sites you visited
  Cell In[140], line 4
    print('z equals 0')
    ^
IndentationError: expected an indented block after 'if' statement on line 3

✅  Question 5.2 (4 Points)#

Why do you think it might be important to have you search error codes to look for answers?

Put your answer here!

✅  Question 5.3 (3 Points)#

In the original Pokemon games you can select an option between three different starter pokemon to have as a companion. There is the water turtle Squirtle, the fire lizard Charmander, and the plant dinosaur Bulbasaur.

Some people make this decision based on the pokemon type that they like.

Write some code using if/else statements that prints out “I choose you squirtle!” if the variable favorite_type is ‘water’, “I choose you charmander!” if the variable favorite_type is ‘fire’, and if the variable favorite_type is ‘grass’ then the if statement should print out “I choose you bulbasaur!”

Make sure you change the variable favorite_type to be different values to test your code!

# Run me for Pokemon pictures!
import urllib.request
from io import BytesIO 
from PIL import Image

url = 'https://static.wikia.nocookie.net/pokemon/images/c/c8/Kanto_Starters_III.jpg/revision/latest/scale-to-width-down/385?cb=20121022074525'
with urllib.request.urlopen(url) as url:
    img = Image.open(BytesIO(url.read()))

display(img)
../../_images/47bad9181f6bf844e360ba6ddfd2ec0e17f710a92738f234acf753a5368f1455.png
# Put your code here!
kanto_starters = ['Squirtle', 'Charmander', 'Bulbasaur']

favorite_type = 'water'

✅  Question 5.4 (3 Points)#

Some people have an order of preference for these starters. Let’s make a decision tree of if statements based on availiblilty and preference. If Charmander is available (the variable charmander = True), print out “Yay I got my number one pick!”. If Charmander is not available (the variable charmander = False) and Bulbasaur is available, print out “Not my favorite, but also not bad!”. If neither Charmander nor Bulbasaur are available, then print out “Welp at least I get a starter!”. If all three (Charmander, Bulbasaur, Squirtle) are not available, then print out “You get Pikachu! It will take some time to warm up to you” followed by another print statement of “What is the type of Pikac-ZZZZZZZZZZRRRRRRRRRTTTTT!!!!……… Ow”

The selections should go in order of preference. What we mean by this is that if two of the pokemon are available, your if statement should only select the pokemon with the higher order of preference and only print out the associated text.

Make sure you test every possible case to make sure your code runs correctly!

# Put your code here!
charmander = True

bulbasaur = False

squirtle = False

✅  Question 5.5 (4 Points)#

a) How do you know that your code is working?

b) How many different cases did you have to try to make sure your code worked for all cases?

c) Did you use if, if and elif, if and else, or if, elif, and else to write this code?

d) Why did you choose this way, and is it possible to write this code in a different way to achieve the same result?

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 © 2024, Department of Computational Mathematics, Science and Engineering at Michigan State University, All rights reserved.