Input
An input statement is used to store what the user types in a variable. The variable name is written on the left of an equals sign, and the message that asks the user for data — the prompt — is written inside the brackets of the input call.
In the statement instrument = input("Which instrument do you play? "), the name instrument is written without quotes, because it is a variable being created, not text. The prompt is a string, so it does need quotes.
To store the value, put the input call on the right of the equals sign and the variable on the left. The left of the equals sign must be a variable name, because that is the place that receives the value. Writing input("Which instrument do you play? ") = instrument is not valid, because a function call is not a variable.
Once the prompt appears, the program stops and waits. Nothing else runs until the user has typed a value and pressed Enter. At that moment the text typed becomes a value and is stored in the variable, ready for later lines to use.
# The answer is kept in the variable so it can be used later
instrument = input("Which instrument do you play? ")
print("Great choice,", instrument)Output when the user types guitar:
Which instrument do you play? guitar
Great choice, guitarA space is not added after the prompt for you, which is why the prompt above ends with a space — without it the user's typing would appear straight after the question mark.
If the input call is written on its own with no variable to receive the value, the value is created but no name refers to it, so it disappears as soon as the line finishes. No later line can print it, calculate with it or check it.
# Only the book title is kept; the page count is not stored
book = input("Book title: ")
input("Number of pages: ")
print("You borrowed", book)Output when the user types The Lost Whale, 240:
Book title: The Lost Whale
Number of pages: 240
You borrowed The Lost WhaleFinally, never use input as a variable name. Names like book or shelf are free to use, but naming a variable input replaces the name of the input function, so later calls to input() will not work.
OCR GCSE Computer Science · Input