Getting input is key to making an interactive program.
User input is the main way of handling this.
first_name = input("What is your name? ")
Note that there is a space at the end of the string inside the input function. Without this the input would start right next to the end of the text in the string.
You can then print out your responses as shown below
Enter the code below and see what happens
Enter any number of icecreams to purchase.
The example above enters 7 a valid answer but the input method saves it as the string “7” we can’t multiply strings.
To do that we put the variable we want to convert inside another function called int().
We can also combine those first two lines together.
But what happens if we enter the word five instead of five?
The program has crashed with an error “invalid literal for int()…” this means that it couldn’t convert the contents of the string “five” to a number.
The code below shows how to prevent these types of errors. The example includes the use of a while loop which will be covered later.
This code will check if the num_purchased congains digits. we use the not keyword do get all the options that are not digits. If there is not a digit entered e.g. “five” it will ask the user to reenter an input until a valid input is entered.
More work on while loops will be given in a later tutorial.