Getting user input and commenting

Hey guys, welcome back to the Python basics tutorial! Now I'm gonna tell you how to get input from the user. Let's say you're trying to make a simple "hello" program.

name = 'Mark'
print('Hi, ' + name)

Right? But the user won't be able to edit the variables themselves, so you need a way of getting input from them. Luckily, Python has a really simple way of doing this:

name = input('Enter your name: ')
print('Hi, ' + name)

Easy, right? Now run the program, the >>> prompt will disappear and you'll see a new prompt "Enter your name: ". Enter your name there and press Enter. You should see 'Hi, {your name}' appear.

Values returned by input are always strings.

To make an adder:

a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
print(a + b)

Run it and enter the values, and you'll see the sum of them printed.

We use int() to convert the inputs to integers to get the expected result as shown in the previous chapter.

Commenting

Let's say you have a really complicated program. You need to explain it to someone. How do you do this? You can't just

The following line prints the value of a.
print(a)

Since "The following line prints the value of a." is not valid Python code, it will cause a SyntaxError. To explain code you use comments which start with a # and are ignored:

# Print the value of a
print(a)

Easy! To make multi-line comments or "docstrings" use triple quotes:

"""
This is a multi line comment also know as a docstring
"""
# This is a regular comment.
print('Hello')

From now on, I'll be using comments to show the output of the code too.

Homework

Get the user's name and age, add them together to make a single string and print it out.

Last updated