Python Tutorial - User Input and Output

Advertisement

Advertisement

View the full playlist on YouTube: Learn Python - Build a Cookbook

Transcript

Hello this is NanoDano at DevDungeon.com with the next video in the Python Cookbook series. The previous videos explain what the cookbook method is and how to get yours started. We wrote a hello world program last time that simply prints out some text, and learned how to commit files to our git repository and push the changes over to GitHub.

In this lesson we will learn how to get input from the user and other ways of getting input and output from a program.

Let's start a new program. In PyCharm, right click the root project folder in the project panel and select New Python File. Name it user_input. Click Yes to add it to git.

In the editor, let's start the program by greeting the user. Type print("hello"). This should look familiar.

Then, let's ask the user their name. There is another function built-in to Python called input(). This will get input from the user. On a new line in the same file type type input()

Run it. What's happening? Notice we don't see the exit status, so the program has not finished running yet. The python interpreter is waiting for our input before moving on to the next line of code (or in this case, ending the excution of the program)

Let's enter some text and press enter. Now it looks like the program has exited as we see the exit code with a note that process has finished.

Also notice how the icons in the left change when a program is running versus not running.

Someone running this program wouldn't know what to do. We should print a message saying Please enter yourname. We could use another print() statement. Let's do that.

Now run it. Well, that's better, but it would be even nicer if the user entered their name on the same line as the prompt asking for their name. Input actually takes a parameter just like the print function. When we pass the input function a string as a parameter it will display the string as a prompt to the user and wait for their input on the same line. Let's see that in action.

Remove the print statement and put a text string inside the parenthesis for the input function. I will put "What is your name? ". Add a space at the end so there is room between our question mark and where the user types in their name.

Now, run it. When we enter our name it is on the same line as our prompt. The user input is green and italicised in the PyCharm console, but it would not normally have any special colors in a regular terminal. Let's run it manually in the terminal to demonstrate.

Open the Terminal tab in the bottom and type python user_input.py. If you are using Linux or Mac with Python 3 you may need to type python3 user_input.py. If you get a message about python not being a recognized command, then you need to update your PATH environment variable to include the path where python is installed.

You may have noticed that after we enter our name and press enter, nothing happens except for the program exiting. Our Python script takes our input but doesn't do anything with it.

Instead of letting the user's name go in to a black hole, let's store it in a variable. At the beginning of the line with the input() function, add "name = ". This variable, named "name" will store whatever value is returned from the input function.

What we want to do in this case is say hello using their name. Create a new line after the input function and add another print statement. Type print("Hello " + name).

The plus sign is normally for adding numbers, but int his case we are "adding" strings, combining them, or concatenating them, creating one larger string from multiple smaller ones.

Have you noticed this yellow squiggly at end of line? Mouse over it or select the bulb. Ah, no newline at end of file. It is best practice, although not strictly required, to have a blank line at the end of the file.

Let's run it again and make sure it works. Everything looks good.

Not all variables are equal though. So far we have only dealt with string variables. We can say hello to a user with their name, but what about numbers? Let's say we want to ask the user for a number and then multiply that number by 3 and print out the result.

Using what we've seen already, let's try to do it the same way. Create an input prompt asking the user for a number. number = input("What is your favorite number? ")

Then let's print number * 3. The asterisk (or star) is the sign for multiplication.

Run it. Hmm, it's still asking us for our name. Let's comment out those few lines for right now since we already know they work and we just want to work on this number part. Highlight the lines above and press ctrl forward slash. This will comment them all out at once. Don't worry, we'll uncomment them later.

A comment is designated by that hash sign. Comments can also be added at the end of a line making anything coming after it a comment, or code that is ignored by the python interpreter. You can add notes to yourself this way too.

Now let's restart the program. We can do that by clicking this icon in the bottom left.

Now it jumps straight to asking us for our number and ignores those lines asking for our name. Let's give it a number, say 23.

It printed out 232323, not 69 like we'd expected. Why is that?

It is because in Python there are different types of variables. Strings, or text variables are treated differently from whole numbers or integers like 1, 2, 3, which are also treated differently from decimal point numbers, or floating point numbers like 3.141592.

So, how do we tell Python we want to use that variable as a number instead of string? We have to convert it from a string to a number. This is called type-casting because we are changing the type of the variable.

Cast the number value we get to an integer so we can work with it numerically. Type triple = int(number) * 3

This is creating a new variable named triple and we are assigning it the value of number * 3. We are explicitly telling Python to use the variable named number as an integer in this operation.

Now lets print out the value to the user. Let's try print("Your number multiplied by three is " + triple)

Run it and enter a number. Uh oh, what is this mess? Focus in on the error message. TypeError: Can't convert integer object to string implicitly.

Ah, the variable triple is an integer value and Python will not add a string and a number together (because that doesn't really make sense).

So we have to explicitly tell Python to use that variable triple as a string. Then it will be smart enough to convert the numerical value to a string value representing that number.

In the print statement, wrap the triple variable with a call to the str() which will typecast the integer to a string.

Run the program again and make sure it works as expected now. Perfect.

Let's also uncomment the lines we commented out earlier and save the file.

It's worth taking a second to talk a little more about variable types

Create a new python file and call it variable_types

Create these three variables with me. my_integer = 3, my_float = 3.141592, my_string = "hello".

There is a built in python function named type that will tell you what type a variable is. Let's print out the type of each of these variables.

We are passing a function as a parameter to another function. What happens here is the inner function gets executed first, that function will get executed first, and the value returned from that function will get printed.

Python variables can change type after they are created. For example, we can change my_integer to be the value of "some text" and print out the type. Now my_integer is a string type. So even though we created it as an integer, there's no guarantee it will always be an integer.

So now we have two more cookbook snippets ready to go. If you ever need to get input from a user or forget how to typecast variables, you have some reference material.

Let's push the changes to GitHub. Right click on the project root folder and go to Git -> Commit Directory.

Both of the files should already have check boxes next to them since we added them to git when we created them. If they don't have check boxes next to them, check them now.

Add a commit message. I will say, "Adding user input and variable type examples". Mouse over Commit, and choose Commit and push and finalize the push.

Your files in the project panel will no longer be green but a normal gray or white color. This means they have been commited to git and there have been changes since the last commit.

Don't worry if you haven't fully grasped each of those topics at this point. Topics will get further explanation as we progress through this series of tutorials.

If you found this video useful keep watching the rest of the series and subscribe to this channel and visit devdungeon.com.

Thanks for watching and keep coding.

Advertisement

Advertisement