Embercode
✕
Variables and Data TypesLesson 1 of 16

45 min read

Your first Python program

Why it matters

Every Python program is a text file with instructions in it. Python reads the file from top to bottom and carries out each line. When a line is wrong, Python stops and prints a message that names the line. If you can read that message, you can find most mistakes in a minute.

This course trains you for data structures and algorithms (DSA) interviews. Interviewers often start with a short program, then ask you to read input, loop, sort or search. Everything in this module sits on top of the basics in this lesson, so go slowly now.

What you need before you start

You need Python 3. Open a terminal and type:

python3 --version

You should see a line such as Python 3.14.4. The course was checked with Python 3.14. If you see command not found, install Python from python.org or from your operating system's package manager. On Windows the command is often python instead of python3.

The Run box on this page also works without any install, so you can finish the first lessons in the browser.

The idea: an interpreter reads your file

A computer chip cannot read Python text. A program called the interpreter does the reading. You start it with the python3 command, and it works in two steps.

  1. It reads the whole file and checks that the text follows Python's grammar, which is the set of rules for valid code. A break of a rule is a syntax error.
  2. It runs the statements one at a time, from the top of the file to the bottom. Each statement finishes before the next one starts.

The standard interpreter, called CPython, also turns the text into a list of low-level instructions called bytecode before it runs them. You do not need to see that step for this course.

Think of a cook who reads a recipe card one line at a time. A syntax error is a card with a word the cook cannot read. The cook notices it before cooking anything, so nothing is made. A runtime error is an instruction that makes sense but cannot be done, such as "add the eggs from the fridge" when the fridge is empty. The cook has already made the dishes from the lines above it.

The next program shows this difference. Python checks the whole file before it runs the first line, so this program prints nothing:

print("This line never runs.")
print("This line has a mistake"
  File "...main.py", line 2
    print("This line has a mistake"
         ^
SyntaxError: '(' was never closed

The path before line 2 depends on where your file is. The rest of the message is what you will see.

Your first program

Create a folder for this course, then create a file named main.py inside it. Copy the program below into the file exactly. Capital letters count.

Python · editable

The output is:

Hello, Python!

On your own computer, run the file from a terminal in the same folder:

python3 main.py

You type the file name with its .py ending. Python runs the file you name, so there is no separate class name to match.

The shape of a Python file

A Python file can be one line. Java needs a class and a main method before anything runs. Python does not. Here are the parts you will use from the start.

PieceWhat it means
print(...)Shows the text or number inside the brackets, then moves to a new line.
"..." or '...'Text, called a string. Both quote styles work. Use the same style for the whole string.
#Starts a comment. Python ignores everything from # to the end of the line.
: at the end of a lineStarts an indented block, which is a group of lines that belong together. You will use it with if, for and def in later lessons.
IndentationThe spaces at the start of a line. Python uses them to decide which lines belong to a block. Use four spaces per level.

Two rules hold for every line. Python is case-sensitive, so print and Print are different names. Only the first is a built-in function. Lines do not need a semicolon.

What happens when the program runs

When you type python3 main.py, the interpreter reads the file, checks it for syntax errors, then runs the top-level lines in order until it reaches the end of the file.

A def line does not run the code inside it. It only stores a function, which is a named group of instructions. The instructions run when some line calls the function by its name. The next program shows the order.

Python · editable
first
second
inside greet
third

Trace it line by line. The first print runs. The def stores greet and prints nothing. The next print runs. Then greet() calls the function, which prints inside greet. The last print runs. The output follows the order of the calls, not the order of the def line.

Each call makes a small record called a frame. The frame holds the function's local names and the place to return to. Frames stack up like plates: a new call puts one on top, and the function's end takes it off. When a call fails, Python's message lists these frames, outermost first and newest last. You will see that list in the error section below.

Printing text and numbers

print shows what you give it. Text in quotes is printed exactly as written. Numbers are printed as numbers. Arithmetic is worked out first, then printed.

Python · editable
Python
42
5
2 + 3
2 + 3 = 5

The third line has no quotes around the sum, so Python adds 2 and 3 and prints 5. The fourth line has quotes, so Python prints the characters as written. The last line uses an f-string, which is text with a f before the opening quote. Anything in braces inside an f-string is worked out and placed into the text. You will use f-strings for most output in this course.

Mixing text and numbers

Python does not turn a number into text for you when you join them with +. Joining text and a number raises an error:

print("2 + 3 = " + (2 + 3))
Traceback (most recent call last):
  File "...main.py", line 1, in <module>
    print("2 + 3 = " + (2 + 3))
          ~~~~~~~~~~~^~~~~~~~~
TypeError: can only concatenate str (not "int") to str

The message says that str, the Python name for text, cannot be joined with an int, the name for a whole number. You have two fixes. Use str(2 + 3) to turn the number into text, or use an f-string as in the earlier example.

print with its options

print ends each call with a new line. Two options change that. The sep option sets the text placed between the arguments, and the end option sets the text placed after the last one. The default for sep is one space and the default for end is a new line.

Python · editable
Java is fun
a-b
One Two Three
Four

Use end="" when you want several calls to build one line. The first two print calls with end="" add to the same line, and the third call ends it.

Escape sequences

Some characters cannot be typed directly inside a string. Python uses a backslash followed by a letter for them. These are called escape sequences.

SequencePrints
\na new line
\ta tab (a wide gap)
\"a double quote
\\a single backslash
Python · editable
Name:	Asha
She said "hello"
C:\projects\forge
Line one
Line two

The tab in the first line is a real tab character, so its exact width depends on your screen. The double quotes in the second line need no escape, because the string is in single quotes. Backslashes are doubled in the source, so the printed path has single ones.

Comments: notes the interpreter ignores

A comment is text for people reading the code. Python skips it completely. Use comments to say why a line exists, not to repeat what the code already says.

Python · editable
Comments are skipped.
Done.

Comments matter in interviews. When you explain your approach out loud, you do the same thing in writing: you say what the next block is trying to achieve.

Reading an error message

An error message in Python has a standard layout. Read it in this order.

  1. The last line gives the error type and a short message, such as IndexError: string index out of range. Start here.
  2. Above it, the File line gives the file name and the line number where the error was found.
  3. The code line is copied under the File line. A caret (^) or tilde (~) marks the part of the code involved.
  4. Lines above that show the calls that were active when the error happened, outermost first. The newest call is the last one before the error type.

The first kind of error is a syntax error. Python checks for these before the program runs, so the message points at the text it could not read:

  File "...main.py", line 1
    if True
           ^
SyntaxError: expected ':'

An if line must end with a colon. The caret sits after the place where the colon belongs.

Indentation errors are the next kind. A block that should be indented but is not gives this message:

  File "...main.py", line 2
    print("Hi")
    ^^^^^
IndentationError: expected an indented block after function definition on line 1

The error names the line that starts the block, def on line 1. The fix is to indent the body of the function by four spaces.

The third kind happens while the program runs. An index is a position in a string or list, counted from 0. Asking for a position that does not exist fails:

word = "Forge"
print(word[5])
Traceback (most recent call last):
  File "...main.py", line 2, in <module>
    print(word[5])
          ~~~~^^^
IndexError: string index out of range

word has five letters, so the valid positions are 0 to 4. Position 5 does not exist. This is a runtime error. Any print above line 2 would already have run.

A name that does not exist gives a NameError. Python's built-in function is called print, so a capital P fails:

Traceback (most recent call last):
  File "...main.py", line 1, in <module>
    Print("Hi")
    ^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?

The last line is the one to read first. It says the name Print was not found, and it suggests print.

Blocks and indentation instead of braces

Java uses curly braces to mark blocks. Python uses indentation. A line that ends with a colon must be followed by lines indented one level further. The block ends when the indentation goes back.

Python · editable
indented
not indented

Both print lines sit at the same level in the file, but only the first one is inside the if. Indentation is part of the code. If a line is indented when it should not be, Python reports IndentationError: unexpected indent. Use four spaces for every level and never mix tabs and spaces in one file.

Functions and the main guard

Many programs put their work in functions and call them from one place at the bottom. Python has a convention for this. A line that checks __name__ decides whether the main code runs.

Python sets the name __name__ to the text "__main__" for the file you run directly. A file loaded by another file gets a different value, so the code under the check does not run in that case.

Python · editable
Built by a helper function

The return line gives a value back to the caller. The text function builds the message, and main prints it. The last two lines start the program. The convention is not required by Python, but nearly every Python program you read will use it, and it lets you import the file later without running its main work.

Tracing a program step by step

Tracing means following a program by hand, one statement at a time, and writing down what has happened so far. Interviewers often ask "what does this print?" You will use tracing for every loop and every recursive call later in the course.

Make a table with one row per statement. Write the output produced so far in the last column. Do not skip rows, even when a row looks obvious.

Python · editable
StatementWhat it addsScreen so far
1. print("Step 1 ", end="")Step 1 with a trailing space and no new lineStep 1
2. print("done")done and a new lineStep 1 done, then a new line
3. print("Step 2 ", end="")Step 2 on the new lineStep 2
4. print("almost ", end="")almost on the same lineStep 2 almost
5. print("done")done and a new lineStep 2 almost done, then a new line
6. print("Step 3 done")the whole text and a new lineStep 3 done, then a new line
Step 1 done
Step 2 almost done
Step 3 done

The easy mistake is to forget the trailing space inside "Step 1 ". Without it the output reads Step 1done. Spaces inside strings are real characters.

When the output matches your table, your mental model is correct. When it does not, find the first row where the two disagree. That row holds the misunderstanding.

Worked example: a small receipt

This program prints a short receipt. Predict the output before you run it. Then compare.

Python · editable
=== Receipt ===
Notebook	80
Pen	30
Total	110
Thank you!

Line 2 joins the text "Notebook", a tab, and the text form of 80, which is 2 * 40. Multiplication happens before joining because * has higher priority than +. The str call is needed because + does not turn a number into text. The total is built from three calls. The first two use end="", so the word, a tab and the number share one line.

Why Python for DSA

Python is a common choice for coding interviews and for competitive programming. Three features make it suitable for learning data structures and algorithms.

First, the code is short. A list, a dictionary and a set are built into the language, so you can focus on the algorithm. You will meet these in the collections lesson.

Second, the syntax reads close to plain English. Most of the code you write for an interview fits on a screen.

Third, the interpreter is strict about some things and loose about others. A list can hold different kinds of values, and a function does not declare its argument types. That freedom makes it easy to write a quick test, but it also means a wrong type shows up at run time. Type hints, which you will meet later in this module, let you state the types and let a checker find mismatches before the program runs.

The cost is speed. For large inputs Python runs slower than compiled languages. Interviewers usually accept Python for DSA questions, and you can often choose a better algorithm to make up for the difference.

Common mistakes

These are the mistakes beginners make in their first hour. Each one has a message you will see.

  • Missing closing bracket. The message is '(' was never closed. Find the bracket the message names and check it has a ) on the same line or a later one.
  • Missing colon. The message is expected ':'. Lines that start a block, such as if, for, while and def, need a colon at the end.
  • Wrong indentation. The message is expected an indented block or unexpected indent. Each block level must be indented by the same amount, and lines outside the block must not be indented.
  • Wrong capitals. Print("Hi") gives name 'Print' is not defined. Python names are case-sensitive.
  • Joining text and a number. "Total: " + 5 gives can only concatenate str (not "int") to str. Use an f-string or str(5).
  • Position out of range. word[5] on a five-letter string gives string index out of range. Valid positions run from 0 to 4.
  • Confusing print options. If your output is on one line when you expected several, you probably forgot end="".

Practice

Try each exercise before you open the answer. Use the Run box to check your work.

  1. Print your first name on one line and your home city on the next line, using two print calls. Then print the same two lines using one print call and the \n escape.

Show the answer

print("Asha")
print("Chennai")
print("Asha\nChennai")

The first two calls print two lines. The third call prints the same two lines.

  1. Print the words Python, is and fun on one line, with a space between them, using three print calls. Put the spaces inside the strings.

Show the answer

print("Python ", end="")
print("is ", end="")
print("fun")

The output is Python is fun.

  1. Print a three-line poem of your choice. Each line must be a separate print.

Show the answer

Any three lines work, for example three print calls with one line of text in each.

  1. Predict the output of print(7 * 6) and print("7 * 6"). Then run both to check.

Show the answer

The first prints 42, because Python multiplies. The second prints 7 * 6, because the quotes make it text.

  1. Print a small table with a header line Item, a tab, then Price, and two rows of your choice. Use \t for the tab.

Show the answer

print("Item\tPrice")
print("Pen\t10")
print("Book\t25")
  1. Print a path such as C:\Users\Ravi so that the backslashes show exactly as written. Use escape sequences.

Show the answer

print("C:\\Users\\Ravi")

Each doubled backslash prints as one.

  1. Write a program with a comment at the top saying what it does. Print one line.

Show the answer

# Prints a greeting.
print("Hi")
  1. Remove the closing bracket on purpose from a working program, run it, and write down the message and the line number. Fix it and run again.

Show the answer

The message is '(' was never closed, and the caret points at the opening bracket on that line. Add the ) back.

  1. Change print to Print on purpose, run the file, and write down the message. Fix it and run again.

Show the answer

The message is name 'Print' is not defined. Did you mean: 'print'?. Change Print back to print.

  1. Write a program that prints the sum of 15 and 27, the product of 4 and 9, and a text line that explains both. Print each on its own line.

Show the answer

print(15 + 27)
print(4 * 9)
print("The first line is a sum, the second is a product.")

The output is 42, then 36, then the text line.

  1. Explain in one sentence to a friend what if __name__ == "__main__": does.

Show the answer

The code under the check runs only when the file is started directly, because Python sets __name__ to "__main__" in that case. When another file imports this one, the check is false and the code is skipped.

  1. Trace this program on paper, then run it to check: print("a", end=""), then print("b\n", end=""), then print("c").

Show the answer

ab
c

The \n ends the line after b, and the print("c") call starts on the new line.

What you now know

  • A Python file runs from the top down. A def stores a function, and the function body runs only when it is called.
  • print shows text and numbers. Its sep and end options control the spaces and the line break.
  • Python does not join text and numbers with +. Use an f-string or str(...).
  • Indentation marks blocks. A line that ends with a colon starts one.
  • Read an error from the last line up: the error type and message first, then the line number.
Practice this topic: coding problems for Variables and Data Types →

Stuck? Ask the tutor

Ask about anything in this lesson. Answers are short and use simple words.

Sign in to ask the tutor.