Modules/Python/ Your First Program

Hello, Python!

Your first program, run in a real Python interpreter that lives right here in the page. Change the code, press Run, and the browser actually executes it.

Overview

Start here

Python is an interpreted language: a program called the interpreter reads your file top to bottom and executes each statement immediately. There is no separate compile step, which is why the editor on this page can show you results the instant you press Run — the interpreter is running your code right in the browser.

Your first line of code

Press Run and watch it print. Then edit the text inside the quotes and run again.

Python 3
Output

                            

A program with several steps

Python reads a file top to bottom, running each statement in turn. Two prints, and a calculation in between.

Python 3
Output

                            

How to read the output

print writes a value to the screen. It is how a program talks to you — everything else on this track builds on seeing what your code actually does.
Quotes mark text. print("Hello") prints Hello, not the quote marks — the quotes are part of the code, not the message.
No quotes means math. print(2 + 3) prints 5, because Python computes the addition before printing. Compare that with print("2 + 3"), which prints the text literally.
Order matters. Statements run top to bottom, one line at a time. Swap the two print lines in the second editor and the output order flips with them.

Hello, Python: A Practical Guide

Running code changes what you believe about it.

The first program, and what it teaches

print("Hello, world!")

One line, and already three ideas are present. print is a function — a named piece of work that already exists. The parentheses are how you call it. The text in quotes is a string, an argument passed in for the function to work on.

Every Python program is built from those three things, repeated. What changes is which functions you call and what you pass them.

Run it and Python reads the file top to bottom, one statement at a time, executing as it goes. There is no compilation step to wait for and no main function required, which is a large part of why Python is a good first language.

What print actually does

print("Hello")                       # Hello
print("Hello", "world")              # Hello world      -- space between
print("Hello", "world", sep="-")     # Hello-world
print("no newline", end="")          # stays on the same line
print()                              # a blank line
print(3 + 4)                         # 7  -- prints the result, not "3 + 4"

Two details worth knowing early. print inserts a space between arguments by default, which explains output like "Hello , world" when a comma is inside the string as well. And it converts whatever it is given into text, so print(42), print([1, 2]) and print(None) all work.

For building a message from values, an f-string is the readable way:

name = "Ada"
age = 36
print(f"{name} is {age} years old")   # Ada is 36 years old

Quotes, comments and indentation

Single and double quotes are equivalent; pick one and use the other when the text contains a quote:

'It is fine'
"He said \"hi\""
'He said "hi"'          # simpler
"""Three quotes
span several lines."""

Comments start with # and are ignored. Write them to explain why, not what — # retry twice because the API drops the first request is useful; # add one to x is not.

Indentation is Python's most distinctive feature: it is part of the syntax, not a style choice.

if True:
    print("indented by four spaces")   # this belongs to the if
print("not indented")                  # this always runs

Four spaces per level is the universal convention. Mixing tabs and spaces produces TabError, which is why every Python editor is configured to insert spaces.

Input, and the first real program

name = input("What is your name? ")
print(f"Hello, {name}!")

input() displays its prompt, waits for the user to type, and returns what they typed as a string, always. That last part causes the first bug most beginners meet:

age = input("Age: ")
print(age + 1)          # TypeError: can only concatenate str to str
print(int(age) + 1)     # correct

Putting it together into something that does a job:

celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius}C is {fahrenheit:.1f}F")

Read input, convert it, calculate, format the output. Most programs are a longer version of exactly that shape.

Guided experiments

  1. Edit the greeting. In the first editor, change the text inside the quotes to your own name and press Run.
  2. Break the quotes. Delete one of the quote marks and press Run. The error you get is Python complaining that it reached the end of the line while still reading a string — the single most common beginner error, and it is perfectly safe to make here.
  3. Numbers vs text. Replace "Hello, Python!" with 2 + 3 (no quotes) and run again. Then run print("2 + 3") and compare the two outputs.
  4. Reorder the steps. In the second editor, move the last print("Done!") to the top of the file and run. The output proves Python executed your lines in exactly the order you wrote them.

Summing up

Everything a program does is the result of statements running top to bottom. print is your window into that — it turns invisible execution into text you can read. And the moment you can change code and see different output, you have moved from reading about programming to actually programming.

Running Python

Three ways, each suited to something different:

  • A file. Save hello.py and run python3 hello.py. This is how real programs are written and shared.
  • The interactive prompt. Type python3 and you get >>>, where each line runs as you press enter. Perfect for trying something out; nothing is saved.
  • A notebook. Jupyter and similar tools run code in cells, keeping the results alongside. Standard for data work; less so for building applications.

In the interactive prompt, an expression's value is shown automatically, so 2 + 2 displays 4 without print. In a file it does not — which is why code that "worked in the console" appears to do nothing when saved to a file.

When it goes wrong

Errors are Python telling you exactly where it stopped and why. The last line is the important one:

  File "hello.py", line 3
    print("Hello)
          ^
SyntaxError: unterminated string literal

Three of the four you will meet in your first week:

  • SyntaxError — Python could not parse the code. A missing quote, bracket or colon. Check the line above the one reported too, since an unclosed bracket is only noticed later.
  • NameError — a name that does not exist. Usually a typo, or using something before defining it.
  • TypeError — an operation applied to the wrong type, most often text where a number was intended.
  • IndentationError — the indentation does not line up.

Reading the message before changing anything saves more time than any other habit in programming.

Statements run in order, one at a time

The single most useful thing to hold on to at the start is that Python does exactly what the lines say, in the order they are written, one at a time. There is no hidden ordering and nothing runs ahead.

That sounds too obvious to state, and it is the thing that resolves most early confusion. A variable used before the line that creates it raises NameError, because that line has not run yet. A print placed before a calculation shows the value before the change, not after. A function defined at the bottom of a file cannot be called at the top, because the def statement has not executed.

It is also the basis of the most effective debugging technique there is: put a print between two lines and see what is true at that point. Not what you believe is true — what actually is. print(f"{value=}") shows the name and the value together, so there is no chance of reading the wrong label against the wrong number.

The habit worth forming in the first week is to reach for that immediately rather than re-reading the code. Re-reading tells you what you meant; running tells you what happened, and the gap between the two is where every bug lives.

Naming things

Python will accept almost any name, and a few conventions are worth adopting from the first program rather than unlearning later.

Lowercase with underscores for variables and functions: user_name, total_price, read_file. Not userName, which is the JavaScript and Java convention and marks Python code as translated from somewhere else.

Say what it holds, not what type it is. names is better than name_list, because the type may change and the meaning will not. Plural for collections, singular for one thing — for name in names reads correctly and tells a reader what each item is.

Avoid names the language already uses. list, dict, str, sum, id, input and type are all ordinary names that happen to be built in, and assigning to one hides the original for the rest of that scope. Nothing warns you; the failure comes later and looks impossible.

Single letters only where the scope is tiny and the meaning is conventional. i for an index in a three-line loop is fine. d for the thing your whole program is about is not.

The reason to care this early is that names are the documentation you cannot avoid writing. A well-named variable removes the need for the comment that would have explained it.

What to do when something does not work

The first week produces a lot of programs that do not do what was intended, and having a routine matters more than knowing any particular fix.

Read the last line of the error first. It names the type of problem and usually describes it in plain English. The line above it tells you where. That is two facts before you have looked at your code at all.

Check the line above the one reported. An unclosed bracket or quote is only noticed when Python reaches the next statement, so a SyntaxError on a line that looks perfect very often means the previous line never finished.

Print the values, not the code. When there is no error but the output is wrong, the question is what the variables actually held. print(f"{value=}") answers it directly, and the = form means the label can never drift out of step with the value beside it.

Change one thing at a time and run again. Two changes at once means an improvement and a regression can cancel out, and you learn nothing from either.

Make it smaller. Cut the input down, or copy the failing few lines into a new file. Most bugs become obvious once everything unrelated is gone, and the cutting itself often reveals the cause.

None of this is specific to beginners; it is what experienced programmers do, faster. The habit that separates the two is reaching for evidence early rather than re-reading the same code hoping to spot it.

Questions people ask

Python 2 or 3? Python 3. Python 2 reached end of life in 2020; any tutorial using print "x" without parentheses is out of date.

Do I need semicolons? No. One statement per line, and the line ending is the terminator.

Do I need to declare variables? No. Assigning to a name creates it.

Which editor should I use? VS Code with the Python extension is the common choice; PyCharm is the fuller IDE; IDLE ships with Python and is fine for a first week.

What is if __name__ == "__main__":? A guard that runs code only when the file is executed directly, not when it is imported by another file. You need it once you start splitting code into modules.

Why does my file do nothing when I run it? Most often because the results are computed but never printed — the interactive prompt shows values automatically and a script does not.

Should I learn the terminal first? Not before writing anything. Enough to run python3 file.py and change directory is plenty for several weeks.

How long before I can build something? Sooner than most people expect. Variables, conditionals, loops, functions and lists are enough for a genuinely useful script.

Does the order of my functions in a file matter? Only that a def must have run before the name is called. Defining everything first and calling at the bottom is the usual arrangement.

What is the >>> in examples I see online? The interactive prompt. Do not type it — it marks the lines you would enter, and the line after it is the output.

Do I need to install anything to follow this track? Not for the editors on these pages — they run Python in your browser. Installing it locally is worth doing once you want to keep files.

Why do examples use python3 rather than python? On many systems python still refers to the old Python 2, or to nothing at all. python3 is unambiguous.

Is indentation really part of the syntax? Yes. The indentation decides which statements belong to which block, and getting it wrong is an error rather than a style complaint.

What is a virtual environment and do I need one yet? A per-project set of installed packages. Not needed for a first program; worth learning before you install your first library.

Why does my program print nothing when it seems to work? Because computing a value and displaying one are different things. A script shows only what you explicitly print.

Recap in one screen

  • print() is a function call; the parentheses do the calling and the quotes make a string.
  • f-strings (f"{name}") are the readable way to mix values into text.
  • Indentation is syntax — four spaces, never mixed with tabs.
  • input() always returns a string; convert with int() or float() before doing maths.
  • Read the last line of an error message first; it names the problem.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does print("Hello") send to the screen?

  2. print(2 + 3) prints:

  3. A program is just:

Cheat sheet

Hello, Python!

Your first program, run in a real Python interpreter that lives right here in the page. Change the code, press Run, and the browser actually executes it.

PYTHON · vizlearn.in/python/hello_python.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.