FACES · PythonMAKE SOMETHING THAT SPEAKS

CODE LAB 01 / FIRST CONTACT

print("Hello")Small messages.
A whole new universe.

Program a greeting. Give your rover a name. Turn a few words into a mission story.

让代码说话:从输出文字,到变量、故事和自己的小作品。

Python 311 chapters9 projects3 guided sessions
Begin the mission ↓
Two young makers and a teal rover exploring coding at a workbench
print("Hello")› Hello
01Send a messagePrint · comments · quotes · lines02Make it personalVariables · types · names · f-strings03Build & shareNine projects · challenges · review

01 / PREPARE THE WORKSPACE

A place to write.
A place to see what happens.代码写在哪里?结果出现在哪里?

A program is a set of instructions. In this lab, you will write Python instructions that send messages to the output area, often called the console.

Your goal

Build a personalized mission postcard using text, a number, variables and an f-string. Add a helpful comment, and remove or disable a temporary test message.

  1. Open our Trinket course ↗ in a second tab and follow your teacher’s sign-in or join instructions.
  2. Open the assigned Python 3 activity. Ask your teacher which workspace to use if the course menu differs.
  3. Locate the code editor and its Run control. Type code into the editor; look for results in the output area.
  4. After each change: predict → run → compare → adjust. Save through the coding tool’s own controls.

网页上的互动是概念演示;完整Python代码请在Trinket中运行。 / The guided models here explain specific ideas; Trinket runs your Python programs.

Keyboard field guide / 常用快捷键
ActionWindows / ChromeOSMac
Copy selected textCtrl + CCommand + C
Paste copied textCtrl + VCommand + V
Undo an editCtrl + ZCommand + Z
Select all in the focused editorCtrl + ACommand + A
Save in many code editorsCtrl + SCommand + S

Shortcuts depend on the app and which area has focus. In a browser, Save may save the web page and New may open a browser window. Use Trinket’s own controls for saving, creating activities and running; do not assume an F5 shortcut runs your code.

Suggested pacing

Session A: chapters 1–5. Session B: chapters 6–9. Session C: projects and review. Allow about 45–60 minutes each and choose extra challenges as needed.

02 / MAKE YOUR FIRST MESSAGE

One instruction.
One visible result.print() 把信息显示出来

print() is a built-in Python function. For our first instruction, put a message between matching quotes, then place that string inside the parentheses.

PYTHON 3 / CODE
print("Hello")

OUTPUT / 输出

Hello
printThe function nameLowercase matters.
( )The call parenthesesEnclose the argument.
"Hello"A stringText inside matching quotes.

The quotes mark the boundaries of the string in the code. print() displays the text without those surrounding delimiters. It also ends with a newline unless you tell it otherwise; we will use its default behavior here.

Predict a short transmission

PYTHON 3 / CODE
print("Mission Control")
print("Rover online.")
print("Ready to explore!")

Predict first. Reveal the output →
Mission Control
Rover online.
Ready to explore!

Now change the second message and rerun. Programs execute these statements in order, from top to bottom.

GUIDED MODEL / MESSAGE PREVIEW

Your first transmission

PREPARED CODE

print("Rover online.")

EXPECTED OUTPUT

Rover online.

This prepares a print statement; copy it into Trinket to execute Python.

QUICK CHECK / 想一想

Which spelling calls Python’s built-in function?

03 / LEAVE NOTES. FIND BUGS.

Be your program’s
careful investigator.用注释解释,用线索调试

A comment is a note for people reading the code. Outside a string, # starts a comment that continues to the end of that physical line. Python does not execute that comment as a statement.

Use comments to explain a purpose or temporarily disable a complete test line. Their color depends on the editor; no particular color is required.

A teal rover inspecting a connector with a magnifying glass
PYTHON 3 / CODE
# Announce the mission
print("Ready for launch")
# print("Testing speaker...")
print("Crew check complete")  # Final status

OUTPUT / 输出

Ready for launch
Crew check complete

The test message is still in the file, but its line is commented out. Once it is no longer useful, you may delete it. Commenting out code helps isolate a problem, but does not by itself repair the underlying mistake.

PYTHON 3 / CODE
print("Dock #7")  # The # inside quotes is text

Predict first. Reveal the output →
Dock #7

GUIDED MODEL / COMMENT SWITCH

Keep or silence a test message

EXPECTED OUTPUT

This model switches one prepared example. It is not a general Python runner.

A repeatable debugging routine

  1. Read: check the error name and the highlighted or reported location. The actual cause may be just before it.
  2. Inspect: compare capitalization, quote pairs and parentheses. Check variable names too.
  3. Change one thing: fix the smallest likely problem so you know what helped.
  4. Run again: compare the actual result with your prediction. Restore any temporarily disabled lines when needed.
NAME ERROR
Print("Launch ready")
Find the repair
print("Launch ready")

In a fresh program, Print is undefined. Use the lowercase built-in name.

SYNTAX ERROR
print("Launch ready"
Find the repair
print("Launch ready")

The opening parenthesis needs its closing partner.

QUICK CHECK / 想一想

Which hash remains visible in the output?

04 / QUOTES & ESCAPE SEQUENCES

Keep the punctuation.
Make the boundaries clear.文字里的引号,代码里的引号

Single quotes and double quotes can both delimit a string. Choose a matching pair. If the text contains an apostrophe, double quotes are often the simplest outer pair.

PYTHON 3 / CODE
print("The rover's lights are on.")
print('The screen says "Welcome".')

OUTPUT / 输出

The rover's lights are on.
The screen says "Welcome".
Why can an apostrophe cause an error?
print('The rover's lights are on.')

The apostrophe after rover closes this single-quoted string too early. Python then encounters characters where the remaining syntax does not make sense. This is a string-syntax problem, not a limit of print().

Another solution is an escape sequence: a backslash changes how the next character is interpreted inside the string.

PYTHON 3 / CODE
print('The rover\'s lights are on.')
print("The screen says \"Welcome\".")

OUTPUT / 输出

The rover's lights are on.
The screen says "Welcome".
\'Include an apostrophe in a single-quoted string.
\"Include a double quote in a double-quoted string.
\\Include one literal backslash.
\nStart a new output line.
PYTHON 3 / CODE
print("Folder: missions\\day1")

Predict first. Reveal the output →
Folder: missions\day1

GUIDED MODEL / QUOTE STUDIO

One message. Two quoting styles.

EXPECTED OUTPUT

Notice which quote characters need a backslash. The output text stays the same.

QUICK CHECK / 想一想

What is the backslash doing in ' inside a single-quoted string?

05 / GIVE TEXT SOME SPACE

Three ways to make
a message breathe.多次print、\n 与三引号

You can use separate print() calls, place \n inside a string, or write a triple-quoted string across multiple source lines.

PYTHON 3 / CODE
print("Earth\nMoon\nMars")

OUTPUT / 输出

Earth
Moon
Mars

The code contains a backslash and a lowercase n; the resulting string contains a newline character. Use \n\n to leave an empty line between two pieces of text.

PYTHON 3 / CODE
print("Launch deck\n\nObservation deck")

Predict first. Reveal the output →
Launch deck

Observation deck

A longer message with triple quotes

PYTHON 3 / CODE
mission_note = """Open the hatch.
Check the stars.
Begin the journey."""
print(mission_note)

OUTPUT / 输出

Open the hatch.
Check the stars.
Begin the journey.

Three opening double quotes match three closing double quotes. Triple single quotes also work. These are string delimiters, not escape sequences, and they do not automatically substitute variable names.

Whitespace is part of the message.

A newline immediately after the opening triple quotes becomes a first blank line. Spaces typed before a text line also become part of the string. Start the first word right after the opening quotes when you want no first blank line, as in this example.

A small history stop: why “line feed”?

Paper-based printing equipment had to advance to another line as well as position the print head. The old ASCII standard distinguishes line feed—moving to the next printing line—from carriage return—moving to the first position on the same line. The names survived in computer text systems. Python’s \n represents a newline in a string.

History reference: RFC 20, control-character definitions.

QUICK CHECK / 想一想

Do triple quotes require an f prefix?

06 / NAMES THAT REMEMBER VALUES

Name it.
Use it. Change it.变量名与值建立联系

A variable name lets you refer to a value. In rover_name = "Pip", Python first evaluates the value on the right and binds the name on the left to that value. The equals sign performs assignment.

rover_name
STRING VALUE"Pip"
PYTHON 3 / CODE
rover_name = "Pip"
print(rover_name)
print("rover_name")

Predict first. Reveal the output →
Pip
rover_name

print(rover_name) looks up the name’s value. print("rover_name") prints those literal letters. Use a variable only after assigning it; otherwise a missing name can produce NameError.

Reassignment changes what the name refers to

PYTHON 3 / CODE
rover_name = "Pip"
print(rover_name)
rover_name = "Nova"
print(rover_name)

Predict first. Reveal the output →
Pip
Nova

GUIDED MODEL / STEP THROUGH ASSIGNMENT

Watch one line at a time

  1. rover_name = "Pip"
  2. print(rover_name)
  3. rover_name = "Nova"
  4. print(rover_name)

CURRENT BINDING

No value assigned yet

OUTPUT SO FAR

0 / 4 lines explored

A useful model, with a limit

The arrow is a way to think about a Python name referring to an object. A Python variable is not necessarily one fixed CPU register or a literal labeled storage box. Changing a name’s binding also does not erase text already printed.

QUICK CHECK / 想一想

After a new assignment, does text already printed change?

07 / SAME DISPLAY, DIFFERENT TYPE

7 and "7"
are different values.整数是数;带引号的是文字

7 is an integer, with type int. "7" is a string, with type str. Both can look the same when printed, so appearance alone does not tell you the type.

PYTHON 3 / CODE
crew_count = 7
dock_code = "7"
print(crew_count)
print(dock_code)
print(type(crew_count))
print(type(dock_code))

OUTPUT / 输出

7
7
<class 'int'>
<class 'str'>

type(value) gives information about the object’s type. In a script, use print(type(value)) to display it. A Python interactive shell may display the value of a bare expression automatically.

GUIDED MODEL / TYPE LENS

Same digits. Different kind of data.

PYTHON 3 / CODE
message = ""
print(type(message))

Predict first. Reveal the output →
<class 'str'>

An empty string "" is still an assigned value. It is useful when you want text with zero characters; it does not mean “unassigned.”

Other types you will meet later
PYTHON 3 / CODE
temperature = 18.5
ready = True
print(type(temperature))
print(type(ready))

OUTPUT / 输出

<class 'float'>
<class 'bool'>

A float can represent a value with a fractional part; bool represents True or False. Lists hold collections. Today’s projects mainly need strings and integers.

QUICK CHECK / 想一想

Which assignment stores an integer?

08 / CHOOSE USEFUL NAMES

A name should help
the next reader.合法、清楚、一致

Syntax rules

  • For our beginner English-letter names, start with a letter or underscore.
  • After the first character, letters, digits and underscores can appear.
  • No spaces or hyphens inside the name.
  • Do not use reserved words such as class or for.
  • Names are case-sensitive: crew and Crew are different.

Readable style

  • Prefer descriptive lowercase snake_case: crew_count.
  • crewCount is camelCase. It can be valid Python, but is not the style used in this lesson.
  • A valid name can still be unclear: x9 tells us little.
  • Avoid replacing built-in names such as print or type with your own values.
PYTHON 3 / CODE
mission_name = "Moon Garden"
crew_count = 7
rover_2 = "Nova"
print(mission_name)
print(crew_count)
print(rover_2)

OUTPUT / 输出

Moon Garden
7
Nova

GUIDED MODEL / NAME CHECKER

Legal name or useful name?

This beginner checker uses English letters, digits and underscores. Python also supports many non-English letters in names. Style advice is separate from syntax validity.

QUICK CHECK / 想一想

Which name is legal but does not follow this lesson’s snake_case style?

09 / BUILD MESSAGES WITH F-STRINGS

Keep the sentence.
Swap in the details.f 前缀 + 花括号里的表达式

An f-string starts with f before its opening quote. Python evaluates expressions in { } when it creates that string and inserts their values into the text. It is a formatting feature, not a backslash escape.

PYTHON 3 / CODE
rover_name = "Nova"
destination = "Europa"
print(f"{rover_name} is heading to {destination}.")

OUTPUT / 输出

Nova is heading to Europa.
fEnable formattingBefore the quote.
{rover_name}Look up a valueThe expression goes in braces.
.Keep literal textText outside braces stays text.
PYTHON 3 / CODE
rover_name = "Nova"
print("Hello, {rover_name}!")
print(f"Hello, {rover_name}!")

Predict first. Reveal the output →
Hello, {rover_name}!
Hello, Nova!

F-strings can insert an integer or evaluate a simple expression too; they do not require every expression to be a previously assigned variable.

PYTHON 3 / CODE
crew_count = 7
print(f"Crew aboard: {crew_count}")
print(f"Extra seats needed: {crew_count + 2}")

Predict first. Reveal the output →
Crew aboard: 7
Extra seats needed: 9

GUIDED MODEL / MISSION CARD MAKER

Change the data. Keep the template.

EXPECTED OUTPUT

This prepares a fixed example from these fields. Run the copied program in Trinket.

Triple quotes and f-strings can work together

PYTHON 3 / CODE
captain = "Mika"
destination = "Moon Garden"
mission_card = f"""MISSION CARD
Captain: {captain}
Destination: {destination}
Status: ready"""
print(mission_card)

OUTPUT / 输出

MISSION CARD
Captain: Mika
Destination: Moon Garden
Status: ready

Triple quotes preserve the source line breaks; the f prefix enables the expressions. These are two independent features. To print a string variable unchanged, print(mission_card) is enough.

A string is a result, not a live link
PYTHON 3 / CODE
station = "Aurora"
report_title = f"Message from {station}"
print(report_title)
station = "Comet"
print(report_title)
report_title = f"Message from {station}"
print(report_title)

OUTPUT / 输出

Message from Aurora
Message from Aurora
Message from Comet

report_title keeps the text that was created earlier. Reassigning station does not go back and change that existing string. Rebuild the title to include the new station value.

Challenge: show braces themselves
PYTHON 3 / CODE
print(f"Write {{name}} as a placeholder.")

OUTPUT / 输出

Write {name} as a placeholder.

Inside an f-string, doubled braces {{ and }} produce literal braces.

QUICK CHECK / 想一想

What is missing from "Welcome, {pilot}" if you want to insert pilot’s value?

10 / THE PROJECT STUDIO

Turn your new tools
into something of your own.九个原创项目,逐步组合

A cardboard rocket exploring a paper-craft solar system with a waving teal rover

Start with one small project, then choose another. The final mission postcard combines the key ideas. These starters are examples to change, not scripts you must copy word for word.

Project 7: the scrambled report to repair
2captain = "Mika"
x = 7
MissionCOLOR = "teal"
print(f"Captain {2captain}: {x} crew, {MissionCOLOR} flag.")

One name is invalid; two could be clearer or more consistent. Write your repair in the workspace. The starter for this task shows one possible solution.

YOUR WORKBENCH / 草稿区

Run in our course ↗

This is a draft editor, not a Python interpreter. Project drafts remain in this tab’s memory when you switch projects; copy or download them before leaving or refreshing. They are not sent to student accounts or Trinket automatically.

Reveal the original starter’s output

This belongs to the original starter. Your edited program may produce different output; run it in Trinket to find out.

11 / MISSION DEBRIEF

Explain it.
Then make it yours.理解比背答案更重要

Text

Matching quotes delimit strings. Escapes can include quotes, backslashes and newlines. Triple quotes can span source lines.

Data

Names refer to values. Reassignment changes the binding. Types distinguish text from integers even when they print alike.

Messages

F-strings evaluate expressions in braces when created. They can be multiline, but triple quotes do not require an f prefix.

Habits

Use clear names, explain useful intentions in comments, predict results and fix one likely issue at a time.

Twelve-question flight check

Feedback is shown here only. This checks concepts, not whether your own Python program runs.

1. Which line displays a greeting in a fresh Python program?
2. What happens to a line beginning with # outside a string?
3. What does print("Bay #2") display?
4. Which escape sequence creates a new line inside a normal string?
5. Which statement is correct about triple quotes?
6. After rover = "Pip", what does print("rover") display?
7. What is the type of 7 without quotes?
8. Which variable name is valid and follows our beginner style?
9. What is the job of f in f"Dock: {dock}"?
10. What does an already-created f-string do after a source variable changes?
11. Which statement is true about message = ""?
12. Where should the final project be run?
Teacher guide, scope and references / 教师指南

This expanded Lesson 1 is an original workshop based on the programming topics visible in the supplied reference scans. Wording, story world, program examples, activities, illustrations and page composition are newly created. No scanned pages or book artwork are published.

Recommended sequence: session A—setup, output, comments, debugging, quote handling and multiline text; session B—assignment, reassignment, types, naming and f-strings; session C—choose several projects, finish the mission postcard and share. The nine projects include introduction, quoted dialogue, changing state, poetry, word substitution, reuse, naming repair, text art and an integrated final program. Use extra projects for later practice rather than rushing every concept.

The two very blurred scanned spreads cannot be read reliably. The lesson covers the legible themes without inventing their unreadable details. Clarifications include: comments can follow code but a hash inside a string is text; variable names may contain later digits; Python names are not assumed to map to CPU registers; an empty string is assigned data; f prefixes and triple-quote delimiters are distinct; a built f-string does not update retrospectively. F-strings require a compatible Python 3 environment (introduced in Python 3.6).

The course link is used as supplied. The signed-in Trinket course has not been edited. The lesson’s guided models are not general Python execution, and typing here does not submit work. Choose a Python 3 workspace for the f-string activities.

YOUR NEXT TRANSMISSION

Ready to see your code work?

Open our Trinket course ↗Back to Python class