Lecture 12 - Decisions

Lecture Date: Monday, September 21

Snow Day At-Home Practice!

In lieu of lecture today, we’d like for you to do the program that we were going to do today in class. Write a program called letter_grade.py that will take a list of grades, separated by spaces, and then calculate the average of those grades. Print to the screen the average along with the letter grade (according to our letter grade system found in the syllabus). The scores are not weighted in any way - just do a straight up average.

So, a run of the program might look like this:

Input your scores, separated by spaces: 90 80 78
Average: 82.667
Letter: B-

Please submit one .py file named letter_grade.py to the grading system. Look for the assignment marked ex1. Note that this is not for a grade! This is for you to practice if elif statements! We have set it to quick feedback, so you should get results within 10 minutes of uploading.

One hint: When you read in a list like shown above, the numbers are actually read in as strs. Which is not what we want. To convert each item in a list to something else (or in fact to call a function on each item in a list), you can use something called a list comprehension.

So, if grade_list is the list of grades that you split from what the user entered, the following will convert grade_list from a list of strs to a list of ints!

1
grade_list = [ int(x) for x in grade_list ]

Original Lecture notes for today are below.

More on if and else today.

Let’s start by creating a grade calculator!

Consider a few different ways of figuring out the letter grade:

  • several if statements
  • if-elif statement
  • by looking at the individual digits of the grade
mod operator
1
2
3
4
5
6
# Prompt the user

grade = int(input("What's your grade? "))

tens = grade // 10
ones = grade % 10

We can intentionally leverage integer division to get the tens place of the grade.

To get the ones place, we will use the modulus operator, which gives us the remainder after division.

We will spend time today touching on the following:

  • Scope (and scope errors)
  • Reviews the logical operators: == != < > <= >= and or not
  • tracing code

Then, we’ll start on loops if we have time, specifically while loops.

while loops
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#Mark Sherriff (mss2x)

index = 1
while index < 10:
    print(index)
    index = index + 1 # or index += 1

# infinite = 1
# while infinite > -1:
#     print(infinite)
#     infinite += 1

value = 5
while value >= 0 and value <= 10:
    value = int(input("Give me a number less than 0 or greater than 10:"))

value2 = -1
while value2 <= -1 or value2 > 10: # this is the bad case
    value2 = int(input("Give me a number between 0 and 10: "))

list_of_names = ["mark" , "tom"]
while len(list_of_names) > 0:
  # do something

No Audio Today due to Snow Day