User Input

The input statement requests and obtains user input:

name = input("What's your name? ")
print(name)

The code segment executes as follows:

  1. First, input displays a prompt to tell the user what to type and waits for the user to respond. In this case, the prompt is the string “What’s your name?”. Imagine, I typed Sonia (without quotes) and pressed Enter.

  2. The input statement then gives back those characters as a string that the program can use. Here we assigned that string to the variable name.

  3. Finally, python displays name’s value, which is Sonia in the case of the example described above.

It is important to note that input ALWAYS gives you a string value. Consider the following snippets that attempt to read two numbers and add them:

value1 = input('Enter first number: ') # Imagine I enter 7 for this prompt
value2 = input('Enter second number: ') # Imagine I enter 3 for this prompt
print(value1 + value2)

Rather than adding the integers 7 and 3 to produce 10, Python “adds” the string values ‘7’ and ‘3’, producing the string ‘73’. This is known as string concatenation. It creates a new string containing the left operand’s value followed by the right operand’s value.

Getting an Integer from the User: If you need an integer, convert the string to an integer using the statement int:

value = input('Enter an integer: ')
value = int(value)
type(value) # This will display int