Using Decisions with Strings¶
Give examples of programs that use conditions with strings.
inputfunction to get input from a user
elifto handle 3 or more options.
strto convert a number to a string.
Here’s an example of conditional execution using
if statements with strings. We can print different strings based on the value of a number. For example, if the user only orders 1 item we can print that out differently than if the user orders more than one item. Notice the use of
str(numItems) in the code below. The function
str turns a number into a string so that it can be appended to a string.
Change the value of
numItems to see how that changes the output.
What if you want different messages to be printed based on the user’s score in a game? The code below should print “You can do better!” if the score is less than 10, “Good job” if the score is between 10 and 19 inclusive, and “Amazing” if the score is 20 or more, but it needs to be fixed. First run it with different values to see what happens and then answer the multiple choice questions below.
Now go back and change the last active code (csp_sd_score) to work correctly. Remember that you can use
and to join two logical expressions. This is especially useful if you want to test if a number is in a range of numbers like 10 to 19 inclusive. So change the example to print the first thing if less than 10, the second thing if it is between 10 and 19 and the third thing if it is 20 or more.