Skip to contentSkip to navigation

Module 01 · Lesson 02

Your First Python Program

Write your first real programs: shape print() output with sep, end and escape sequences, and follow Python's rules for lines, indentation and comments.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Show many values
  • Pick the gap and the finish
  • Escape codes and text art
  • Read a syntax error

Your print() toolkit

Last lesson, `print()` showed one thing at a time. Today it learns three new tricks.

  • Commas

    Put commas between values and print() shows them all on one line, with one space between each.

  • sep picks the gap

    sep= swaps that space for anything you like: a dash, a colon, or nothing at all.

  • end picks the finish

    end= swaps the new line at the end, so the next print() carries on along the same line.

Neat output is everywhere

Programs talk to people through text laid out just right. Each of these is a few print() lines.

  • Game scoresThe Lives: 3 | Score: 1200 bar at the top of a game is a few values with a chosen separator.
  • Progress barsLoading dots that grow along one line come from end=, one print at a time.
  • ReceiptsShop tills line up items and prices in neat columns with tabs and a row of dashes.
  • TicketsCinema and train tickets print the same layout every time, with a new name and seat filled in.

One line, three settings

This one line uses everything above. Tap each part to see its job.

Part 1 of 9

Tap any part of the code below, or press Next.1 of 9 explored

command:print shows values on the screen, the same command you met in the last lesson.

Prints Lives: 3!

Shape your own output

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Many values

Commas let one print() show several things, text and numbers mixed.

Your turn: Add a line that prints your three favourite foods on one line.

Python
print("Player:", "Mo")
print("Lives:", 3)
print("red", "green", "blue")
Output
Press Run to see what it prints.

Order matters: robot round two

Python runs your lines top to bottom, exactly as written. These mazes need more turns, so plan the order before you press Go.

Level 1 of 3Down the steps

The robot starts top left, facing right.

1. Add moves

2. Your program (0/14)

Tap the moves above to write your program.

Watch a ticket print, line by line

Press Step to run one line at a time. Watch which lines print and which do not.

Ready. Press Step to run the first line.

  1. # A ticket for the school trip
  2. place = "Zoo"
  3. print("TICKET")
  4. print("Trip", place, sep=": ")
  5. print("Seat\t12")
  6. print("=" * 10)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.What does this print?

print("x", "y", "z", sep="")

0 of 6 answered

Line rules, busted

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Shaping output and writing clean lines

You met print() in the last lesson. It can do more than show one piece of text. Give it several values separated by commas and it shows them all on one line, with a single space between each.

Try it 1: edit me, then Run
print("Score:", 42)
print("red", "green", "blue")
Output
Press Run to see what it prints.

This prints Score: 42 and red green blue. Notice that you can mix text and numbers in one call; print() turns each value into text for you.

Choosing the separator with sep

The space between values comes from a setting called sep, short for separator. You change it by writing sep= and a string after the values. A setting written as name=value inside the parentheses is called a keyword argument.

Try it 2: edit me, then Run
print("2024", "06", "15", sep="-")
print("a", "b", "c", sep="")
Output
Press Run to see what it prints.

The first line prints 2024-06-15. The second uses an empty string, so the values touch: abc.

Staying on the same line with end

After it has shown everything, print() adds an invisible new line character, so the next print starts on a fresh line. The setting end controls what is added instead.

Try it 3: edit me, then Run
print("Loading", end="...")
print("done")
Output
Press Run to see what it prints.

Output: Loading...done. The first call ended with three dots instead of a new line, so the second call continued on the same line.

Quotes and escape sequences

Strings can use double quotes or single quotes; "hi" and 'hi' are the same value. Pick the kind that is not inside your text: "It's sunny" works because the apostrophe is not a double quote. When you need a special character inside a string, write a backslash and a letter. This pair is called an escape sequence.

Try it 4: edit me, then Run
print("Line one\nLine two")
print("Name:\tAda")
print("She said \"hi\"")
Output
Press Run to see what it prints.

\n starts a new line, \t inserts a tab, and \" puts a double quote inside a double-quoted string. A string can also be joined to another with + and repeated with *: "ab" + "c" is abc and "-" * 5 is -----.

One statement per line

Python reads one statement per line. You do not end lines with a semicolon. Blank lines are allowed and make code easier to read. If a statement is long, you may split it inside parentheses, because Python knows the statement is not finished until the bracket closes.

Try it 5: edit me, then Run
print("This message is long, so it is split",
      "across two lines inside the brackets.")
Output
Press Run to see what it prints.

Indentation is part of the language

Many languages use curly braces to group lines. Python uses indentation, the spaces at the start of a line. A line that ends with a colon, such as if True:, starts a block, and every line of that block is indented by the same amount, usually four spaces. You will use blocks with if, loops and functions soon. For now, the rule to remember is that you must not indent a line for no reason: an unexpected indent is a IndentationError.

Try it 6: edit me, then Run
if True:
    print("inside the block")
print("outside the block")
Output
Press Run to see what it prints.

Comments

Anything after # on a line is a comment and Python skips it. Good comments explain why the code does something, not what it obviously does. A comment can sit on its own line or after code on the same line.

Try it 7: edit me, then Run
# Show the opening hours for the shop sign
print("Open", "9", "17", sep=" | ")  # | between the parts
Output
Press Run to see what it prints.

Python is case sensitive, quotes must come in matching pairs, and brackets must close. When a line breaks one of these rules Python reports a SyntaxError and points at the place it got confused. Check the line it names and the one just before it.

Reading a syntax error

A SyntaxError is different from the errors you met in the last lesson. Python finds it before running anything, while it reads the whole file, so not even the first line runs. The message shows the line, and a row of ^ marks under the spot where Python gave up. That spot is often just after the real mistake. If Python says a bracket was never closed, the missing bracket may be on an earlier line, because Python kept reading in the hope of finding it. Fix the first error reported, run again, and repeat; one mistake can confuse Python about the lines that follow.

A habit worth building

Before you press Run, say out loud what you expect to see. Then compare. When the output differs, you have learned something specific about how Python works, and that is exactly how experienced programmers learn a new tool. The Labs for this lesson start with a prediction task for that reason.

Syntax

The general shape of the statements in this lesson.

syntax.py
print(a, b, c)               # values separated by one space
print(a, b, sep=", ")        # choose the separator
print("text", end="")        # no new line after the output
"line\nnext"  "a\tb"  "\"quoted\""   # new line, tab, quote
"ab" + "c"   "-" * 3          # join and repeat text
# comment: skipped by Python
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A neat shop receipt

Beginner

Print a small receipt with a title line, two items with prices separated by a tab, and a dashed line made with string repetition.

Python
print("RECEIPT")
print("-" * 12)
print("Tea\t2.50")
print("Cake\t3.00")
print("-" * 12)
print("Total", "5.50", sep=": ")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

"-" * 12 repeats the dash twelve times, so you do not have to count them by hand. Each \t lines the prices up in a column. The last line uses sep to put a colon and a space between the label and the amount.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

A missing closing quote

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
print("Hello)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

SyntaxError: unterminated string literal

Write this instead

print("Hello")

Why it happens

Python sees the opening quote and keeps reading text, looking for the matching closing quote. It reaches the end of the line without finding it.

In the real world

Where this shows up in software people use every day.

  1. A label for a parcel

    Small business

    Someone selling crafts online prints a short label for each parcel, with the name, the town and the order number laid out the same way every time.

    Why Python fits

    Using sep and string repetition keeps the layout identical for every label. Changing the values is all it takes to print the next one.

    Python
    print("To:", "Sam Lee")
    print("Town:", "Leeds")
    print("Order", "1042", sep=" #")
    print("=" * 16)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Should I use single or double quotes?

Either works. Pick one style and stay with it, and switch only when the text itself contains that quote.

Why does print("a" + "b") show ab with no space?

+ joins strings exactly as they are. Use print("a", "b") if you want the space that separate values get.

How many spaces should I indent?

Four spaces per level is the standard in Python. The editor on this site inserts four spaces when you press Tab.

Can I put two statements on one line?

Python allows it with a semicolon, as in print(1); print(2), but almost nobody writes code that way. One statement per line is easier to read and to fix.

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Score 80% or more on the lesson quiz to mark it complete (+5 XP). Every lesson in a module unlocks that module's Lab.

Complete with the quiz
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.