8  User Input and Changing Variable Types

8.1 User Input

Sometimes we need to ask the user to input something in order to continue with the program.

In Python, getting input from the user is easy. We simply tell Python that we need an input, any message we want to display to the user, and the name of the variable in which we want to store the input.

age = input("How old are you?: ")
Important

HOWEVER, when we read in the inputs from a user, regardless of what it is supposed to represent, they will be read in as a sequence of characters. In other words, as a string.

Clearly, if we’re reading in something intended to be a number (like an age) that’s no good. So what can we do?

Well, we are wizards…

8.2 Casting

Python allows us to turn one type of variable into another, like a magic spell. This is known as casting. As long as the value stored in the variable can be interpreted as the type we’re trying to cast it into, it’ll work (otherwise we’ll get an error).

To cast, we simply wrap the variable on which we’re performing the cast in brackets, and tell it the type of variable we want it to become.

age = input("How old are you?: ")
int(age)

We could also do that all in one line of code :

age = int(input("How old are you?: "))

This will only work if the user inputs something that can be interpreted as an integer. “42” will work. “Too old” will not work.

Warning

Note - you can cast a float value (e.g. 42.6547) as an integer (it’ll just ignore the decimal place and create an int value of 42 - it won’t round).

HOWEVER, this won’t work for strings - you can’t cast “42.6547” as a string into an int.