</>CodexBash
Python
PythonBeginner8 min

Your first Python program

What Python is, how to run a program, printing to the screen, comments, and how to read an error message without panic.

Python is a programming language designed to be read. Its code looks close to plain English, it needs very little ceremony, and it runs as soon as you write it. That makes it the most common first language in the world, and one of the most used by working engineers too.

Hello, world#

The tradition is to start by printing a greeting:

print("Hello, world")

That is the whole program. print is a function: a named piece of behaviour. The brackets hold what you give it, and the quotes mark Hello, world as text, which programmers call a string.

Running it#

Save the line in a file called hello.py and run it from a terminal:

python3 hello.py

On Windows the command is usually python or py instead of python3.

You can also type python3 on its own to open the interactive shell, where each line runs the moment you press Enter. It is the quickest way to try something out:

>>> 2 + 3
5
>>> print("hi")
hi

The >>> is the shell waiting for you; you do not type it.

Printing more than one thing#

print takes several values separated by commas, and puts a space between them:

print("Total:", 42)
print("a", "b", "c")
print()            # an empty line

Output:

Total: 42
a b c

Comments#

Everything after a # on a line is a comment. Python ignores it; it is there for people.

# Work out the area of a rectangle
width = 4
height = 3
print(width * height)   # 12

Good comments say why, not what. The code already says what.

Indentation matters#

Most languages use braces { } to group lines. Python uses indentation: the spaces at the start of a line. You will meet this properly in the lesson on conditions, but know it now, because it is the first thing that trips people up:

if 3 > 2:
    print("three is bigger")    # indented: belongs to the if
print("this always runs")       # not indented: runs either way

Use four spaces per level. Mixing tabs and spaces causes errors that are hard to see.

Reading an error#

Sooner or later you will see something like this:

Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    prnt("Hello")
NameError: name 'prnt' is not defined

Read it from the bottom. The last line says what went wrong (prnt is not a name Python knows, because it is misspelled) and the lines above say where (hello.py, line 1). Most errors are a typo, a missing quote or bracket, or wrong indentation.

Key points#

  • print(...) shows values on the screen; strings go in quotes.
  • Run a file with python3 file.py, or experiment in the interactive shell.
  • # starts a comment.
  • Indentation is part of the language, not decoration.
  • Read errors from the last line up.

Next: storing values in variables, and the kinds of value Python has.

Create a free account to track your progress