User input

You're going to be learning about If Statements soon. But first, let's discuss how you can get input from a user. We'll get a person's age and print out a message, depending on how old the user is.

 

User Input

Start a new project for this. Type Logic for the project name. Add a new Python file to your project and call it IfStatements (we'll be adding these in the next lesson).

To get something from the user, you can use the input function. You use it to the right of an equals sign. You then place whatever the user types straight into a variable. Add this line to you blank Python file:

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

So the input function needs two round brackets. Between round brackets, you type some text surrounded by quotation marks, either single or double. The text you type will stay on the screen until the user responds. You can then do something with whatever the user typed.

Add this print statement as the second line of your code:

print("You entered", age)

Now run your code. You should see this in the output area at the bottom of PyCharm:

Python output window waiting for user input

You need to click inside the output area, just after your text message:

Output window - python

Now enter an age:

An age enetered into the output window

Press the enter key on your keyboard. When you do, Python will assign whatever you typed to the variable that we called age. The age variable is then printed out, along with our message from the print statement:

Output of a user

Python Exercise

In a previous section, you used the tkinter message box. Display a person's age in a message box instead of using print. You should see this:

Tkinter message box - Python

Now that we have a simple input box, let's try some If Statements. We'll do that in th enext lesson below.

If Statements >