User input (text based) in Python (basic) and Validated user input in Python

One way to have data in your code is to get it from external sources such as databases, another computer, the Internet, etc. The options are endless(sort of). Depending on what your code is about you will find that user input is quite valuable if you know what to do with it, we shall see more about this later on. First, we need to see how to get it.

Python makes this super easy for you because it has a built-in function which is unsurprisingly called input.

To declare an input you just add a parenthesis and type your prompt. In the example below I ask for someone’s age or you can get more complex data by creating lists or dictionaries with the input.

n = input(“Please enter your age: “)

The computer kind of replaces “Please enter your name:” with whatever the user writes, which is a prompt string. And when the function is evaluated the input is shown. Remember that whatever the user types, even if it is a number or a character, will ultimately be a string. If you want to use it in any other way then you would use other functions such float or int to modify it.

So in the code above, the variable n is replaced by whatever the user inputs, according to my example if I were to use my short program n will become my age as a string. The next piece of code shows you how to convert it into an integer using the int function.

n = input(“Please enter your age: “)

age = int(n)

I simply created a new variable called age and the value of my variable is mainly the user input but the function int before the name of the variable changes my age as a string intomy age as an integer. Allowing me to work with it.

So what happens if the user input does not match what you’re asking for? You validate it using =.

n = input(“Please enter your age: “)

if n == int:

print(“You look younger!”)

else:

print(“Not a number!”)

Conditionals are useful for this. My code above validates their input by asking whether n is an integer if it is not it prints “not a number” and if it is an integer it prints a very fake compliment.

CC BY 4.0 Mastery28 & Mastery29 by 5nbpppkkyj is licensed under a Creative Commons Attribution 4.0 International License.