Reference · module 9
Input and small programs
Everything this module explains, on one page.
input
Read something the user types.
- input() waits for a line to be typed and hands it back. It always returns a string, whatever was typed.
- Its argument is the prompt shown before the cursor: input("Your name: "). No print is needed for it.
- To do arithmetic on it, convert first: int(input(...)). Forgetting this is why 2 + 2 becomes 22.
The mistake you are about to make
input() + 1
int(input()) + 1
A person types a number, so a number ought to arrive. Input always returns text, which is why "2" plus "2" gives "22" rather than 4.
Checking what came in
Refuse bad input politely.
- int() crashes on anything that is not digits, so a program that trusts the user crashes on a typo.
- text.isdigit() answers whether every character is a digit, so it can be asked before converting.
- Wrap the whole thing in a while loop and it keeps asking until the answer makes sense.
The mistake you are about to make
int(input("Age: "))
check isdigit() first, then int()
It works fine while you are the one testing it. The first typo from a user crashes it on the int(): ask isdigit before converting.
print in detail
Control how output looks.
- print takes as many values as you like and puts a space between them: print(a, b, c).
- sep changes what goes between, end changes what goes after. print(a, b, sep="-") joins with a dash.
- end="" stops the line break, so the next print continues on the same line.
The mistake you are about to make
print("Age: " + age)
print("Age:", age)
Plus only joins things of the same type, so a number here raises a TypeError. A comma joins nothing: print shows both and puts a space between them.
Putting it together
Read, decide, report.
- Almost every small program has three parts: read the input, decide something, report the result.
- Keeping them apart makes it readable. Cramming the decision into the print hides what the program does.
- Give the middle step a name. status = "pass" if score >= 50 else "fail" says the rule in one place.
The mistake you are about to make
the decision squeezed inside the print
the decision on its own line, with a name
Folding the condition into the print hides the thing the program is for. Give the middle step a name — status = … — and the rule lives in one place.
Comments and names
Write code that explains itself.
- Everything after # on a line is ignored by Python. It is there for the person reading.
- A comment repeating the code is noise: # add one above n += 1 says nothing the line did not.
- Explain WHY instead. And where a name can carry the meaning, rename rather than comment.
The mistake you are about to make
# add one above n += 1
# move on to the next day
A comment that restates the code is noise: the line already says it. Explain why — and where a name could carry the meaning, rename instead of commenting.