InterviewPrepKit

Home / Learn / Algorithms & Data Structures with Python

How Python Runs Your Code

This track starts from nothing and builds up to solving real coding problems. This first lesson is about the ground floor: what a program is, how Python turns your text into actions, and the handful of ideas every later lesson leans on.

What a program is

A program is a list of instructions a computer follows in order, top to bottom. You write those instructions as plain text in a file (a .py file) or type them one at a time into an interactive prompt. Python reads your text, checks it makes sense, and carries it out.

The simplest instruction prints something to the screen:

print("hello")
# -> hello

print(...) is a function — a named action you can call. The text in quotes is the value you hand it. Running the line makes Python display that value.

Values and types

Everything Python works with is a value. Each value has a type that says what kind of thing it is and what you can do with it.

print(42)          # -> 42        an integer (whole number)
print(3.14)        # -> 3.14      a float (decimal number)
print("hi")        # -> hi        a string (text)
print(True)        # -> True      a boolean (True or False)

The type matters because it decides how an operation behaves. + between two numbers adds them; + between two strings joins them:

print(2 + 3)          # -> 5
print("2" + "3")      # -> 23

That second line is not a mistake: "2" and "3" are text, so + glues them into "23". Mixing types that do not fit raises an error instead of guessing:

print("2" + 3)        # -> TypeError: can only concatenate str to str

Reading errors is a normal part of programming. The last line names what went wrong; here, Python refused to add text to a number.

Variables: naming values

A variable is a name that refers to a value, so you can reuse it. You create one with =, which means “assign,” not “equals”:

score = 10
score = score + 5
print(score)      # -> 15

Read score = score + 5 right-to-left: compute score + 5 (which is 15), then make score refer to that new value. A name always points at exactly one value at a time.

Names should describe what they hold (total, user_age), use lowercase words joined by underscores, and cannot start with a digit.

How Python runs a file

When you run a file, Python does not jump straight to executing it. The diagram below has a branch off to the side: a serious enough mistake is caught up front, and nothing runs at all.

flowchart LR
  A["Your .py file<br/>(text)"] --> B["Parse:<br/>is it valid Python?"]
  B --> C["Compile to<br/>bytecode"]
  C --> D["Execute:<br/>run instructions<br/>top to bottom"]
  B -. "syntax error" .-> E["Stop before<br/>running anything"]

First it parses the whole file to check the grammar. If a line is malformed (a missing quote or bracket), you get a SyntaxError and nothing runs at all. If the grammar is fine, Python translates the file into a compact internal form called bytecode and then executes it one instruction at a time. Errors that only show up while running (like the TypeError above) happen during that third step, at the moment the bad line is reached. You do not manage any of this by hand, but knowing there is a parse step (grammar) and a run step (behavior) explains why some mistakes stop everything up front and others only surface partway through.

Comments

Text after a # on a line is a comment: Python ignores it. Comments are notes for humans.

# count how many items are in stock
stock = 7      # start of day

Common pitfalls

  • = is assignment, == is comparison. x = 5 stores 5 in x; x == 5 asks whether x is 5 and gives back True or False. Mixing them up is one of the most common beginner bugs.
  • Integer vs float division. 7 / 2 gives 3.5 (a float), while 7 // 2 gives 3 (whole-number division). Choose the one you mean.
  • Indentation is part of the syntax. Python uses leading spaces to group lines (you will see this with if and loops soon). Inconsistent indentation is a SyntaxError, not a style nitpick.

Practice

  1. Predict the output of print(5 // 2), print(5 / 2), and print(5 % 2), then run them. (% is the remainder.)
  2. Set name = "Ada" and print "hello " + name.
  3. Write a line that assigns total = 3 + 4 * 2 and print it. Is the answer 14 or 11? Work out why.
Report a bug