13.1. Using Decisions with StringsΒΆ

We can use conditional statements in code to produce different strings for different situations and to treat different strings in different ways. As a first example, here is a program that prints a different message depending on how many item(s) a person orders. Try this program a few times and enter different values for the input.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

In the program, notice that we have to use the int function to turn the input from a string into an integer. Anytime we use input to get some input from the user, it will be read as a string. If the user types 20, that will be stored by Python as the string "20" and not as the numeric value 20. Any time we get input, if we want to work with it as a number and not as a string (a piece of text that may have digits in it) we will need to use this trick.

Similarly, when we go to construct the string that is the elif response, we are trying to combine the string "You ordered " with numItems a number. As we have seen before, to make this work, we need to call the str function to make a string out of the number that can be added to the other strings.

You have attempted 1 of 3 activities on this page