Unit 1 · the note
Lesson map
The note and the name tag
First you speak. Then you keep what the person said. print, the .py file, input, f-strings, numbers. The recipe you invent yourself (def) waits until unit 4 — once the queue has worn your hand out.
print, variables, keyboard, arithmetic. The index on the left lists every block. Functions with def: unit 4, after the fork in the road and the queue.
Step by step
A file that ends in .py
Make a folder anywhere. Inside it, a file called recado.py. The .py extension is a note to you and to your tools: “this is Python”, not an email.
Write code in a plain text editor. Word, Google Docs and Excel keep hidden formatting; the interpreter wants characters, not bold. VS Code, Cursor, Vim or even Notepad will do.
- Open the editor. New file. Save it as
recado.py. - Write one line of Python (we get to
printin a moment). - Open the terminal in that folder and call the interpreter, passing it the file name.
$ python recado.py
$ — it only marks “your turn”.
The $ (or > on Windows) only marks “your turn”. It is not money. You do not “open the note”. You call the interpreter and pass it the file name.
What the computer actually runs
The processor does not understand print. It understands far lower instructions — in practice, patterns of zeros and ones. You do not write those by hand. The interpreter (the program called python) reads your file, translates it, and puts the machine to work.
That is why the command has two halves: on the left, who translates; on the right, the text to be translated. Without Python installed, the command does not even exist. With it installed, the file is still only text — until someone asks for it to be read.
Serious editors colour the code (keywords in one colour, text in another). That is called syntax highlighting. It is useful make-up: it helps the human eye. The interpreter ignores colour; it only reads characters.
As far as the processor is concerned, what does recado.py contain?
Two doors: terminal and window
CLI (command line interface) is the terminal: you type, the program answers in text. GUI (graphical interface) means windows, buttons, icons — WhatsApp on your phone, your browser.
Both exist. Finished programs almost always use a GUI. To learn the flow line by line, the terminal wins: every command is visible, every error shows up in writing, and no magic click hides what happened.
In this course the default setup is editor plus terminal. Later you can put a window in front of it. The logic underneath stays the same.
In this course, why do we start with the terminal instead of a window with a “Run” button?
What does the command python recado.py do?
The first tool: print
A function is a tool with a name. print writes on the screen. Inside the parentheses goes the argument — the ingredient of the moment. Quotes mark a piece of text (a string).
print("Coffee is ready.")
$ python recado.py
Coffee is ready.
What shows up in the terminal is an effect: something visible. Further along you will meet functions that also (or instead) return a value for you to keep.
Single or double quotes are both fine, as long as the one that opens matches the one that closes. Plenty of people pick double quotes and stay there for the whole course — consistency helps you read.
If the text needs quotes inside it, switch the type on the outside: print('ele disse "oi"'). Or escape them: print("ele disse \"oi\""). The backslash gives notice: the next character does not close the string; it is part of it.
Write the line that prints exactly Coffee is ready.
print("Coffee is ready.")When the computer refuses
Forget the ) at the end. To a human that is a typo. To Python it is half a sentence. It answers with SyntaxError and runs nothing. The messages are sometimes clear (“never closed the parenthesis”); sometimes they guess wrong. With practice you read what matters: the line it points at and the kind of error.
print("Coffee is ready."
SyntaxError: '(' was never closed
This is not a personal failure. It is the contract of the language: either the grammar closes or nothing runs. Fix it, run it again. In the terminal, the up arrow brings back the last command; Tab completes file names.
There is another family of problem: the file runs, but does the wrong thing. That is a logic bug, not a syntax one. The interpreter does not complain — the grammar is fine. You are the one who complains, looking at the screen. The two repairs are different: one is punctuation; the other is thinking.
If the ) is missing from print("Coffee is ready.", what happens?
Notes for humans, not for the screen
A line that starts with # is a comment. The interpreter ignores it. It is for you a week from now, not for “explaining the obvious” in a two-line program.
# morning note — shows up only in the file, not in the terminal
print("Coffee is ready.")
Bigger block: three quotes in a row (""" or ''') open and close a text of several lines. Used as a docstring at the top of a function (module 04) or, the old-fashioned way, as a long comment. It is not print: on its own it never reaches the terminal.
A draft in plain language (sometimes called pseudocode) is worth writing before you type Python: “ask for the name; strip the spaces; print the name tag”. Then you swap each sentence for a real line. No official format needed. Clarity needed.
print with several arguments
print takes zero, one or many values, separated by commas outside the quotes. By default it puts one space between them and, at the end, breaks the line. The documentation says it like this: positional arguments (order matters) and keyword parameters (you call them by name).
sep changes the separator. end changes what comes at the end (the default is \n, “new line”).
print("SP", "Brazil", sep="-")
# SP-Brazil
print("item", end="")
print("seguido")
# itemseguido — the second print carries on the same line
end="" is the empty string: no line break. Useful when you build the line in pieces (it comes back in module 06). print() with no argument emits only the default \n — a blank line.
Positional: print("a", "b") — the order is the order of the commas. Keyword: sep="-" — the name sep, an =, the value. You do not leave the dash loose and hope Python guesses.
Print RJ and Brazil on the same line, separated by /, using sep.
print("RJ", "Brazil", sep="/")Two prints on the same line: the first one must use end so it does not break the line on its own.
print("item", end="")Where print's contract is written down
The specification has an owner: the documentation at docs.python.org — print. That is where the full signature lives: several objects, sep, end, and other details we do not need yet.
It is worth the habit of opening it, even when the page looks dense. This course translates the essentials; the docs are the source if the material and the interpreter ever disagree.
Workshop · card in the terminal
print. Save it as cartao.py and run it in the terminal. Here on the page, paste the code to check that there are three prints.
Paste a program with at least three print calls.
print("Nícolas")
print("engenharia de software")
print("n@empresa.exemplo")Ask and receive
input shows an invitation and waits for Enter. What the person typed comes back to the program — a return value. print only had an effect on the screen; this one hands you an object to use.
input("Apelido: ")
If you do not keep what comes back, it is gone. It is like someone saying their name at the counter and nobody writing it on the name tag.
Ask, receive, label
A variable is a drawer with a label. The = does not ask whether the two sides are equal. It copies from the right to the left: what input returns goes into the drawer called nickname.
nickname = input("Apelido: ")
Descriptive names beat one-letter names: that is what the keyboard is for. Letters, digits and _; never starting with a digit; no reserved words (if, and print as a variable name only gets in the way).
Once it is stored, print(nickname) — no quotes — shows the contents. With quotes, it shows the word.
print("Olá, nickname") prints the word nickname. Quotes = raw text. The drawer is only read without quotes — or inside an f-string, in the next block.
nickname = "Bia" and then print("Oi, nickname"). What shows up?
Notes in the text file
A line that starts with #: the interpreter skips it. It is for you a week from now. Several lines? Several #.
# front desk record
nickname = input("Apelido: ")
Three quotes ("""...""") turn into a block of text. At the top of a function that becomes documentation (a docstring). Loose in the middle of the file, Python builds the string and throws it away — it prints nothing. Printing is print's job.
A file has # fila da manhã and, below it, print("senha 12"). What does the terminal show?
f-string: the default from here on
An f stuck in front of the quotes switches substitution on. Braces in the middle of the text pull the value out of the drawer:
nickname = input("Apelido: ")
print(f"Crachá: {nickname}")
There are other ways (concatenating with +, several arguments in print). They exist and are sometimes useful. In this course, if the sentence mixes fixed text and a variable, start with the f-string. Fewer commas in the wrong place, fewer doubled spaces.
nickname already exists. Print a sentence that includes its value, with an f-string.
print(f"Crachá: {nickname}")Gluing text without an f-string
+ between two strings glues them. "Bem-vindo, " + nickname makes you remember the space by hand. print("Bem-vindo,", nickname) gets a space for free — and one space too many if you already put one inside the quotes.
Mixing a number and a string with + gives a TypeError. Then it is either an f-string or str(n). In module 03 numbers arrive for real; the message here is: the + of strings is not the + of a calculator.
People do not type things neatly
A space at the front, everything lowercase, a nervous Enter. Strings come with tools called methods: the drawer's name, a dot, the tool's name, parentheses.
nickname = nickname.strip().title()
strip removes spaces from the ends (not from the middle). title puts a capital on every word — better for “ana souza” than capitalize, which only touches the first letter of the whole string. The result has to go back into the drawer with =; otherwise you cleaned it up and threw it away.
You can chain it onto input:
nickname = input("Apelido: ").strip().title()
Line getting too long? Break it into two assignments. Readable beats “fits on one line”.
Update nickname: no spaces at the ends, every word capitalised.
nickname = nickname.strip().title()Left side only, right side only, counting
lstrip cleans the left; rstrip the right; strip both. None of them removes a space in the middle of the sentence. That is what replace is for, or other tools later on.
queue = " 12 "
print(queue.lstrip()) # "12 "
print(queue.rstrip()) # " 12"
count counts how many times a piece appears. "banana".count("na") is 2: the pair na in the middle and at the end — not the letter a on its own (that one appears three times).
Write a line that strips spaces from the left of queue only (method lstrip, or the right only with rstrip).
queue = queue.lstrip()What is "banana".count("na")?
Other text tools
| Tool | Typical use |
|---|---|
len(s) | How many characters (a function, not a method) |
s.lower() / s.upper() | Lower / upper case — compare without caring about capitals |
s.replace("a", "b") | Swap a piece |
s.startswith(".py") | Prefix test (comes back in unit 1) |
len is a function: it goes in front, with parentheses. The others are methods: they go after the dot. Spaces count. len("Ana ") with two spaces at the end is 5.
What is len("Ana ")? (two spaces at the end)
Breaking a full name apart
split slices the string at a separator. With a space, “Ana Souza” becomes two pieces. Python lets you unpack them:
primeiro, ultimo = "Ana Souza".split(" ")
print(f"Na lista: {primeiro}")
If the person types three names, that line breaks: more pieces than drawers. The workshop only asks for a simple first name and surname. You handle the rest later.
primeiro, ultimo = "Ana Souza".split(" "). What is the value of primeiro?
Workshop · the front desk name tag
Crachá: … with an f-string. Suggested file: cracha.py.
Paste the name tag program (input + strip + f-string).
name = input("Nome completo: ").strip().title()
print(f"Crachá: {name}")The keyboard does not send an int
File cafe.py: the price of the coffee times the quantity. The naive version:
price = input("Preço unitário: ")
qtd = input("Quantos: ")
print(price * qtd) # TypeError: str does not multiply like that
Swap * for + and the classic shows up: "12" + "3" becomes 123. Concatenation, not addition. int and float are types and also converter functions.
Why does "12" + "3" come out as 123?
Converting for real
Cents ask for float. A whole quantity asks for int. Nesting is valid: the inner one runs first.
price = float(input("Preço unitário: "))
qtd = int(input("Quantos: "))
total = price * qtd
print(f"Total: {total:.2f}")
If the person types bolo, float blows up — decisions in unit 1 sort that out. Today we assume cooperation, but you already know where the program is fragile.
str(n) goes the other way when you need to glue a number into text without an f-string.
One line: read the price (with cents) and store it in price.
price = float(input("Preço unitário: "))Talking to the interpreter
In the terminal, python without a file name opens the >>> prompt. Every line runs on the spot. Handy for trying type(x), a bit of arithmetic, a round. It does not replace the file: close it with exit() or Ctrl+Z on Windows (Ctrl+D on Unix) and go back to the .py when the snippet is worth keeping.
>>> type(3)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("12")
<class 'str'>
How do you get into the mode where every line runs on the spot, with no file?
Arithmetic Python already knows
+ − * /plus, minus, times, divide (this last one already returns a float)
// and %integer quotient and remainder
**power ·
pow(2, 3) is the same as 8abs(-8) drops the sign. min(4, 9, 1) and max(...) pick the extremes. Integers in Python 3 have no practical ceiling; floats have finite precision — 0.1 + 0.2 is sometimes not the 0.3 of the notebook. For money, round when you display it.
What is 10 % 3?
What is 10 // 3?
Two decimals on the screen and in the drawer
round(total, 2) rounds the value. The f-string {total:.2f} only controls the look on the screen — the number in the drawer may still carry more decimals. Choose: round for real (round) or only format (f-string). On a receipt, the two together are common.
por_pessoa = total / pessoas
print(f"{round(por_pessoa, 2):.2f}")
The remainder % comes back in unit 1 for the even/odd queue. Here it already exists: 10 % 3 == 1.
Round the variable total to two decimal places (one call to round).
round(total, 2) or total = round(total, 2)Big numbers in an f-string
In an f-string, {n:,} asks for a thousands separator in the style of the language documentation (a comma: 1,000). In Brazil the eye expects a dot: 1.000. You can switch the locale later; the native syntax is that comma inside the braces. It is not print's sep — it is formatting of the number itself.
vendas = 12500
print(f"Hoje: {vendas:,}")
# Hoje: 12,500
An f-string that prints the variable n with a thousands separator (:,).
print(f"{n:,}")Workshop · the table pays
mesa.py.
Paste the table program (float, division, print).
conta = float(input("Conta: "))
pessoas = int(input("Pessoas: "))
cada = (conta * 1.10) / pessoas
print(f"Cada um: {cada:.2f}")