Home » Chapter 2 : Programming Basics
User Input
So far, the variables and data values we have seen have been hardcoded, that is, we've written the data values directly in our code. This is not a very common approach in programming. More often we acquire data from outside of our programs, for example, by reading a file, querying a database, or prompting the user to type in values. Prompting a user is called user input. In Python, to prompt a user for a value, we use the input() function.
The general form of the input() function is:
variable = input("user_prompt")
age = input("Plese enter your age: ")
The user would see Please enter your age: on the screen and the cursor would be positioned to the right of the prompt on the same line. When they type in a value and press Enter, their entry is assigned to our variable, age in this example.
It is important to be aware that anything the user types will be read by the input() function as a string (str) data type, even if they enter numbers. Consider the following code example:
age = input("Plese enter your age: ")
print(age)
print(type(age))
In programming we often need to convert values of one data type into another data type, this process is called casting. There are two types of casting: implicit and explicit. Implicit casting is automatically handled by the Python interpreter when needed, for example, when dividing two integers and the resulting value is a floating-point number. Explicit casting is when the programmer uses built-in functions to intentionally cast one data type to another.
Let's take a look at examples of implicit and explicit casting with some code.
Implicit Casting Example: Consider the following code:
x = 10
y = 3
z = x / y
print(z)
print(type(z))
We have not yet learned how to do math with Python (we'll get to that over the next few pages), but simple division is accomplished using the division symbol in Python (/). From simple mathematics though, we know that dividing 10 by 3 will not produce a whole number (integer), rather it will result in a decimal number (float). Python automatically sets the appropriate data type of our variable z because the result of the division is a floating-point number rather than an integer and this is implicit casting.
variable = cast_function(expression)
x = "999"
print(x)
print(type(x))
x = int(x)
print(x)
print(type(x))
Explain the above code example and the output.
One possible problem we have with user input is, what if the user types in something we do not expect? For example, reusing our input function code above:
age = input("Plese enter your age: ")
print(age)
print(type(age))
Say a user runs this program and enters something like this: