13.1. Using Decisions with Strings

Learning Objectives:

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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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.

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted 1 of 7 activities on this page