Return to Course Home Page


Practice 2-1: Control Flow Statements

⬅️ Previous Session | 🏠 Course Home | ➡️ Next Session |

control.jpeg

📚 Practice 1

In programs, if statements are useful for catching errors due to user input.

Define two new variables based on user input using the input function.

The first input should prompt for a temperature value and the second input should prompting for the units as “F” or “C”.

Using the equation below, write an if statement that converts the temperature input to °C if it was given in °F or to °F if given in °C. Recall that all variables assigned based on user input are strings (type is str), so you will need to convert the result of your first input statement into a float.

Be sure to comment your code.

Formula for conversion between °F and °C: T_{^{\circ} C} = (T_{^{\circ} F} - 32) \times 5/9

Describe your strategy here before attempting to write any code:

Code
# Add your code here:

📚 Practice 2.

Using nested if statements and your code from Practice question #1, convert the user input temperature to the opposite units (°F to °C or vice versa), print a statement to the user that reports the temperature in the converted units and indicates whether or not the temperature below freezing.

Your print statement should look something like:

The temperature is {__}°C/F. It is (not) below freezing.

Describe your strategy here:

Code
# Add your code here:

📚 Practice 3.

  1. The six organic elements are ‘C’, ‘H’, ‘N’, ‘O’, ‘P’, and ‘S’. Look up their atomic masses and create two lists; one containing the list of elements and the other containing their corresponding masses.

  2. Use enumerate() in a for loop to print a formatted statement that expresses the atomic mass of of each element. Your formatted print statement inside the for loop should include the name of the element and it’s corresponding atomic mass.

    Describe your strategy here:

    Code
    # Add your code here:

📚 Practice 4.

The cell below contains monthly global land-ocean surface temperature in °F for each month during the years 2015-2021. Run the cell before starting on the problem below.

Code
# Import numpy for mean calculations
import numpy as np
import matplotlib.pyplot as plt
# NOTE:
# np.mean can be used to take the average of a list:

tempF_2015 = [61.628,   61.7, 61.808, 61.448,  61.52, 61.538, 61.394,  61.52,  61.61, 62.042, 61.988, 62.168]
tempF_2016 = [62.186, 62.546, 62.528,  62.06,  61.79,  61.52,  61.61, 61.916, 61.718, 61.682, 61.736, 61.628]
tempF_2017 = [61.916, 62.132, 62.168, 61.772, 61.718, 61.376, 61.556, 61.646, 61.466,   61.7, 61.664, 61.754]
tempF_2018 = [61.556,  61.61, 61.664, 61.682, 61.556, 61.466, 61.556, 61.448,  61.52, 61.916, 61.556, 61.718]
tempF_2019 = [61.754,  61.79, 62.186, 61.898,  61.61,   61.7, 61.772,  61.79, 61.754, 61.898, 61.862, 62.042]
tempF_2020 = [62.186, 62.312, 62.186, 62.114, 61.898, 61.736,   61.7, 61.646, 61.862, 61.664,  62.06, 61.538]
tempF_2021 = [61.538, 61.232, 61.664,  61.43, 61.484, 61.592, 61.736, 61.556, 61.736,  61.88, 61.772,  61.61]

# List of yearly lists (may or may not be useful)
tempF_list = [tempF_2015, tempF_2016, tempF_2017, tempF_2018, tempF_2019, tempF_2020, tempF_2021]

# List of years (probably useful)
years = [2015, 2016, 2017, 2018, 2019, 2020, 2021]
  1. Use a zip command to create a for loop that prints out the data across all years for each month. Modify the code below so it would work for your problem:

    
    # The following lists include exam scores for 10 students across 
    # two assessments. Each item in the list corresponds to the same student.
    #
    # For example, the third student's grades are:
    #       midterm_grades[2] and final_grades[2] and 
    
    midterm_grades = [88, 90, 97, 80, 85,  96, 79, 88, 85, 95]
    final_grades =    [99, 87, 93, 86, 81, 100, 87, 91, 76, 90]
    homework_grades = [90, 98, 96, 89, 92, 99, 90, 87, 96, 100]
    
    # Use zip to print each student's grades:
    for midterm_grade, final_grade, homework_grade in zip(midterm_grades, final_grades, homework_grades):
        print(f"Midterm: {midterm_grade}, Final: {final_grade}, Homework: {homework_grade}")
    Code
    # Add your code here:
    1. Alter your for loop so that instead of printing the values, you instead obtain an average of each month’s temperature across all the years of data. Again, here’s what that would look like for our student grades:

      Note: The loop below puts all the iterators produced by the zip command into a single temporary variable, student_grades. Storing them all together in one collection makes it easier to average the values.

      
      avg_student_grades = []
      for student_grades in zip(midterm_grades, final_grades, homework_grades):
          print(f"This student's grades: {student_grades}")
          # Take the mean using np.mean:
          this_student_average = np.mean(student_grades)
          # Append this average to the list of avg_student_grades:
          avg_student_grades.append(this_student_average)
      Code
      # Add your code here:
      1. The mean global surface temperature calculated over the 20th century was 15.6°C. Convert the average monthly temperatures you obtained in the previous step from Farenheit to Celcius. In addition, subtract the mean global surface temperature from each average value to determine the average monthly anomaly from the global average temperature.

        Code
        # Add your code here:
        1. Create a new list containing month labels:

          months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        2. Use this list of months and your calculated average monthly anomalies to create a bar graph showing the average anomalies for each month. The plt.bar function requires at least two arguments: x and y values. Using our student grade examples, the following code would make a bar graph showing each student’s average grade:

          
          # Use range to create x data (student 1-10)
          plt.bar(range(1,11), avg_student_grades)
          
          # Add axes labels
          plt.xlabel('Student Number')
          plt.ylabel('Average Grade')
          
          # Add a title
          plt.title('Average Student Grades')
          Code
          # Add your code here:
          1. Does the graph look like what you expected? Why do you think you see the patterns that emerge from this analysis?

Write your answer here: