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.
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:
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:
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
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:
Easy! To make multi-line comments or "docstrings" use triple quotes:
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
Was this helpful?