13.2. Comparing Strings¶
We can also work with user input directly in string form. If the user is supposed to enter
a word or other piece of text, it makes no sense to try to convert that to a number. Fortunately,
the comparison operators like ==
, !=
, >
, etc… all work with strings.
This program is something like we might have in part of a text based adventure game where the user is trying to navigate a maze:
- The room is pitch black.
- This line will be printed when the user enters in.
- A ghost appears at the end of the hall.
- This line will printed when the user enters left.
- A greenish light is visible in the distance.
- This line will printed when the user enters right.
- None of the above is printed.
- None of the conditions will be true if the user enters something other than in, left, or right so none of these will be printed.
What is the printed if the user answer something other than in, left, or right?
Now it is your turn to write a program that makes decisions with strings. In the program below, you job is to write the function that will turn a letter grade like “A” into the GPA points it is worth: 4. That function will be used to calculate the GPA of someone who took three classes.
Notice that there is some commented out code that hardcodes in three input values. Hardcoded values are ones that are written into a program instead of coming from outside as the program runs (like from user input). Sometimes, hardcoding some values makes it easier to test a function like the one you need to write - you can run the program and immediately see the result instead of having to type in all the inputs every time you run it. Then, once you get the function working, you can remove the hardcoded values and start using real input.
Write the code for the getGPAPoints
function. It should return the GPA points for the
given letterGrade
. An "A"
should result in 4, a "B"
in 3, a "C"
in 2,
a "D"
in 1, and an “F” in 0.