Why this matters
A program that prints the same thing every time is a fancy text file. Programs become useful when they react to input: a name, a number, a file, a request. This lesson gives you the simplest input channel, reading lines that a user types (or that another program sends through a pipe), and introduces variables to hold what you read. By the end you will write programs that compute answers from data they did not know in advance.
Variables, briefly
To work with a value later, you give it a name:
width = 3
height = 4
area = width * height
print(area)
12
width = 3 is an assignment: evaluate the right-hand side, then make the name on the left refer to the result. = here does not mean "is equal to" in the math sense; read it as "let width refer to 3". The next module explains precisely what a name is in Python (a label attached to an object) and why that matters. For now, a variable is a name for a value.
Names may contain letters, digits and underscores, cannot start with a digit, and are case-sensitive (total and Total are different). By convention Python uses lowercase_with_underscores.
input()
The built-in function input() reads one line from standard input and returns it as a string, with the trailing newline removed:
name = input()
print("Hello,", name)
$ python3 greet.py
Ada
Hello, Ada
When the program reaches input(), it pauses until a line arrives. In a terminal that means until you type something and press Enter.
You can pass a prompt that is printed (without a newline) before waiting:
name = input("What is your name? ")
This is friendly for humans, but the prompt text goes to stdout, so it becomes part of the output. In learnprog exercises, call input() without a prompt unless told otherwise, so your output matches exactly.
What is really happening: stdin
Remember the three standard streams from the last lesson. input() reads from stdin (file descriptor 0). In a terminal, stdin is connected to your keyboard, line-buffered by the terminal driver, which is why nothing is delivered until you press Enter. But stdin can just as well be a file or another program:
$ echo "Grace" | python3 greet.py
Hello, Grace
$ python3 greet.py < name.txt
Hello, Ada
The program does not know or care where the line came from. This is how learnprog tests your code: it runs your program with the test input fed into stdin and captures stdout. It is also how real Unix tools are combined into pipelines.
Strings versus numbers
input() always returns a string, even if the user types digits. Watch what happens:
a = input() # user types 3
b = input() # user types 4
print(a + b)
34
For strings, + means concatenation (joining), so "3" + "4" is "34". To do arithmetic, convert the strings to numbers with int() (whole numbers) or float() (numbers with a fractional part):
a = int(input())
b = int(input())
print(a + b)
7
Read int(input()) from the inside out: input() runs first and returns, say, "3"; then int("3") turns it into the integer 3. int() tolerates surrounding whitespace and a leading sign: int(" -42 ") is -42.
Going the other way, str() converts a number to text, which you need when joining with +:
age = 36
print("Age: " + str(age))
print("Age:", age) # print converts for you
Both print Age: 36. Mixing types with + without converting fails, as you will see below.
A complete small program
Convert a temperature from Celsius to Fahrenheit:
celsius = float(input())
fahrenheit = celsius * 9 / 5 + 32
print(celsius, "C is", fahrenheit, "F")
$ echo 100 | python3 temp.py
100.0 C is 212.0 F
Input, processing, output, in three lines. Notice float prints with .0; formatting numbers nicely is covered in the strings module.
Two more arithmetic operators are handy right away:
//is floor division: divide and round down to a whole number.17 // 5is3.%is modulo: the remainder.17 % 5is2.
Together they split a quantity into units, for example minutes into hours and minutes, as in the last exercise.
Common mistakes
Doing math on strings.
n = input()
print(n + 1)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(n + 1)
~~^~~
TypeError: can only concatenate str (not "int") to str
Python refuses to guess whether you meant "5" + "1" or 5 + 1. Convert explicitly.
Converting text that is not a number.
n = int(input()) # user types: twelve
ValueError: invalid literal for int() with base 10: 'twelve'
int("3.5") fails the same way: int of a string accepts whole numbers only. Use float("3.5") for decimals. Later, in the exceptions lesson, you will catch this error and ask again instead of crashing.
Reading more lines than exist. If stdin runs out (the input had one line, but you called input() twice), you get:
EOFError: EOF when reading a line
EOF means "end of file": stdin is closed and there is nothing more to read. Check how many lines the input really has.
Using a prompt in exercises. input("Enter a number: ") adds Enter a number: to stdout and the output will not match.
Recap
- A variable is a name for a value, created by assignment
name = value. input()reads one line from stdin and returns it as a string without the newline. stdin may be a keyboard, a file or a pipe.- Convert with
int(),float()andstr();+joins strings but adds numbers. //is floor division and%is the remainder.- Typical errors:
TypeErrorfor mixing str and int,ValueErrorfor unconvertible text,EOFErrorwhen input runs out.
Going further: run a program that uses input() in a terminal and press Ctrl-D instead of typing a line, to see EOFError yourself. Then try printf '3\n4\n' | python3 main.py to feed several lines at once.