Read Input in Python from the Console

Will Button
InstructorWill Button

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

Getting input from the user via a console command can be done with input in Python. Learn how to implement it and validate user input in this lesson.

Man: In Python, we can receive input from the user using the Python input function. I'll create a variable called name, and then call the input function. We'll provide a string inside of that which is going to serve as our prompt to the user. Then we're just going to print out the results.

To run that, type the Python 3 command followed by the name of my file, and it prompts me for my name. When I enter it, it returns it. So that's for Python 3.

If it try to do it with Python 2, when I enter my name, it errors out. The input function is only for Python 3. To do the same thing with Python 2, we need to use raw input. If we change it to raw input and try that again, it works just like the Python 3 example did.

Once we have that variable from the input, we can use it just like we would with any other variable in Python. We can format a statement here that says, "Hello," inserts their names and say, "Nice to meet you." We'll insert their name with the format method. If we run that, it returns the name formatted inside of the string.

We can use this same pattern to prompt for multiple inputs as well. I can prompt for the name, I can prompt for the job and I can prompt for location and then combine all of that into a single print statement. Say, "Hi," insert their name, insert their job, and their location and use our format operator or our format method to grab those variables of name, job, and location.

Now if we try that out, we'll insert my name, my job, and where I'm at, and it returns a print statement. We can even make this a little bit interactive. We'll get a response from them. Let's say if they respond with yes or a Y or a yeah, we'll respond with, "How exciting." Or if they give us a negative response such as no, N, or nope I guess, we'll print out that's too bad.

Finally we'll say, "I thought so too," if they give us something that's not either positive or negative.

Let's run that now. My name's Will, occupation, code monkey, location is Arizona. There's our printed response. It says, "Is it?" I'll just say yeah. It says, "How exciting."

Everything we give through the input function is a string. If we try to do something like grab one number and then prompt them for a second number and then print out the sum of those two numbers, watch this. We'll enter one and two, and it prints our 12, which is not what we want, because it's two strings. When you add two strings together, it just concatenates them.

We need to convert those to integers. If we try that again, we get the response we were looking for, which was three.