Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

First steps in Python: first program, variables and types

By updated

Improve this page

Logo Python

Python installs in two commands on Linux, and a first program fits on one line: print("Hello, World!"). This lesson starts from zero. You install the interpreter (the program that runs your code), you write and run a script (a text file that contains code), you store values in variables, you discover the four basic types (int, float, str, bool) and you learn to read the most frequent error messages. By the end, you can also make a script executable like a command. Allow 30 to 35 minutes, examples included, plus about thirty more minutes for the optional exercise at the end.

What you will learn

  • Install Python 3 and check the installed version.
  • Write a .py file, run it, and try instructions in the interactive interpreter.
  • Create variables, name them properly and know their type.
  • Convert a value from one type to another, and understand why Python refuses some conversions.
  • Do calculations, work with text and combine conditions with and, or, not.
  • Make a script executable with a shebang and chmod +x.
  • Read the last line of an error to find its cause.

Prerequisites

No programming knowledge is required. You only need to know how to open a terminal and type a command in it (the prompt and the terminal), and how to move between directories (navigating files). Have a text editor ready (Visual Studio Code, Sublime Text, nano, or the one that comes with your system) and, on Linux, sudo rights to install a package.

How do you install Python and check its version?

Python is an interpreted language: a program called the interpreter reads your file and runs the instructions (the orders written in the program) one by one. Installing Python therefore means installing this interpreter. Choose the tab for your system.

Terminal window
sudo apt update
sudo apt install python3

If the package manager is new to you, the apt guide explains it.

Then check that the installation worked:

Terminal window
python3 --version

You get the version number, for example Python 3.12.3 on Ubuntu 24.04 or Python 3.13.5 on Debian 13. You need Python 3.11 or newer. Python 3.10 has not been maintained since 1 October 2026 (release calendar). A 3.9 version is too old as well: its error messages are poorer than those shown in this lesson (invalid syntax instead of invalid decimal literal, without the Did you mean suggestion). On Windows, type py --version.

To install several versions side by side, see pyenv (in French) and uv (in French).

How do you write and run a first Python program?

A Python program is a simple text file with the .py extension. Create a working directory, open your editor and type this single line:

print("Hello, World!")

A function is a command already provided by Python, which you call by its name followed by parentheses. Here, print() displays on screen what you give it between the parentheses. The text is surrounded by quotation marks: it is a string. Save the file as hello.py, open a terminal in that directory and run it:

Terminal window
python3 hello.py
Hello, World!

You have just written and run your first program. The diagram below shows the two ways to run a script: calling the interpreter yourself (the one you just used), or directly with ./hello.py, which requires a shebang and the execute permission, both covered further down. In both cases, it is the python3 interpreter that prints the result in the terminal.

Diagram: the hello.py file can be run in two ways. With python3 hello.py, you call the interpreter directly. With ./hello.py, after a chmod +x, the system reads the first line of the file, the shebang #!/usr/bin/env python3, and starts the python3 interpreter itself. In both cases, python3 runs the script and prints Hello, World! in the terminal.hello.pyplain Python textpython3 hello.py./hello.py(after chmod +x)the system reads#!/usr/bin/env python3python3interpreterHello, World!in the terminal
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The interpreter's interactive mode

Started without a file, the interpreter opens an interactive session: you type an instruction and Python answers right away. It is a good testing ground for a new notion, with no file to create.

Terminal window
python3

The prompt >>> shows that Python is waiting for an instruction:

>>> print("Hello, Python!")
Hello, Python!
>>> 2 + 3
5

In this mode, the value of an expression (a calculation that produces a result, like 2 + 3) is displayed without print(). Quit with exit() or with Ctrl+D (Ctrl+Z then Enter on Windows). In this lesson, lines that start with >>> are meant to be tried here; the others can go in a file.

Indentation delimits blocks

Where other languages use braces, Python groups instructions by indentation: an offset at the start of a line, four spaces by convention (PEP 8). An if condition gives a first glimpse: it runs the indented line only if the condition is true (5 > 3 reads "5 is greater than 3"):

if 5 > 3:
print("5 is greater than 3")

If you forget the indentation, Python refuses to run the program:

if 5 > 3:
print("5 is greater than 3")
IndentationError: expected an indented block after 'if' statement on line 1

Python actually displays a few more lines (the traceback, explained at the end of the lesson). The error examples in this lesson show only the last line, the most useful one.

The message says exactly what is missing: an indented block after the if. Conditions and loops are covered in control structures and collections (in French); for now, remember that indentation is part of the syntax.

What is a variable in Python?

A variable is a name that refers to a value kept in memory. You create it with the = sign, called assignment: the name on the left receives the value on the right.

name = "Alice"
age = 30
height = 1.75
is_adult = True
print(name, age, height, is_adult)

Python asks for no declaration of a type: the variable exists as soon as a value is assigned to it, and its type is deduced from that value. This is dynamic typing. You can later assign it a value of another type, but this is not a good habit: a variable should keep the same meaning from start to finish.

Variable names follow a few rules:

  • they contain letters, digits and the underscore _, with no spaces;
  • they never start with a digit;
  • they are case-sensitive: name and Name are two distinct variables;
  • the convention is snake_case (lowercase words separated by _, like is_adult) and a name that says what the variable contains.

The first two beginner errors come from these rules. Writing Name instead of name gives:

name = "Alice"
print(Name)
NameError: name 'Name' is not defined. Did you mean: 'name'?

Python does not know Name, and it suggests the closest name. As for a name that starts with a digit, it is rejected as soon as the file is read:

2nd_attempt = 1
SyntaxError: invalid decimal literal

Python reads 2nd as a badly written number, hence this message that says nothing about variables: rename it to attempt_2 or second_attempt.

What are the basic data types?

The type of a value determines what you can do with it: you add numbers, you slice text. Four basic types are enough to get started.

TypeFull nameHoldsExample
intintegera whole number, positive or negative42
floatfloating-point numbera decimal number, written with a dot3.14
strstringtext between single or double quotes"Hello"
boolbooleana truth value: True or FalseTrue

The decimal separator is the dot, never the comma. To find out the type of a value, the type() function answers. Take the variables from the previous section (in the same file, or the same interactive session):

print(type(name), type(age), type(height), type(is_adult))
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>

So age = 30 is an int and height = 1.75 a float, without you having specified it. Booleans are written with a capital letter: True and False.

How do you convert a value from one type to another?

Python does not mix types for you. Adding a text and a number is an error:

"123" + 1
TypeError: can only concatenate str (not "int") to str

You have to convert explicitly, with the functions named like the types: int(), float() and str().

>>> int("123") + 1
124
>>> float("123")
123.0
>>> str(30) + " years"
'30 years'

The result '30 years' appears between quotes in interactive mode, which shows the representation of a value; with print(), you would read 30 years. Some conversions fail: int() does not accept a text that contains a decimal point.

int("12.5")
ValueError: invalid literal for int() with base 10: '12.5'

Go through float() first, then int(). Note that int() truncates: it cuts off the decimal part instead of rounding.

>>> int(float("12.5"))
12
>>> int(3.99)
3

Finally, bool() follows a simple rule: an empty or zero value gives False, any other gives True. Beware, what counts is the presence of text, not its meaning.

>>> bool("")
False
>>> bool("False")
True
>>> bool(0)
False

To put a variable inside a sentence without going through str(), f-strings (f"{name} is {age} years old" gives Alice is 30 years old) are covered in formatting a string (in French).

What are comments for?

A comment is text ignored by Python, written for humans: you in six months, or a colleague. It starts with the # symbol and stops at the end of the line. It can take up a whole line or follow an instruction.

# Compute the sum of two numbers
total = 5 + 3
name = "Alice" # a comment can also follow the code

A good comment explains why something is done, not what the code already says: total = 5 + 3 # adds 5 and 3 adds nothing. A script often carries a header at the top giving its purpose, its author and its date, as you will see below with the shebang.

Which operations can you perform on variables?

Variables are used to calculate, to assemble text and to set conditions. Three families of operators cover the starting needs: mathematical, textual and logical. An operator is a symbol that combines values.

Mathematical operations

Python knows the seven usual arithmetic operators. With a = 10 and b = 3:

OperatorRoleExampleResult
+additiona + b13
-subtractiona - b7
*multiplicationa * b30
/divisiona / b3.3333333333333335
//floor divisiona // b3
%modulo (remainder of the division)a % b1
**powera ** b1000

One detail trips up beginners: the / division always returns a decimal number (float), even when it divides evenly, since 10 / 2 is 5.0. For a whole-number result, use //. The modulo % gives the remainder: 10 % 3 is 1, since 10 = 3 * 3 + 1. It is used, for example, to test whether a number is even (n % 2 is 0). Dividing by zero raises an error:

1 / 0
ZeroDivisionError: division by zero

Working with strings

Strings are combined and sliced with a few basic operations.

string1 = "Hello"
string2 = "Python"
print(string1 + ", " + string2) # Hello, Python
print(len(string1)) # 5
print(string1[0]) # H
print(string2[0:3]) # Pyt
print(string2[-1]) # n
print("ab" * 3) # ababab

Concatenation with + glues two strings end to end, and len() gives the length.

Indexing with string1[0] designates a character by its position, and the first position is 0, not 1. A negative index counts from the end: [-1] is the last character.

Slicing with string2[0:3] extracts a slice: it starts at index 0 included and stops before index 3, hence Pyt (three characters, not four). Finally * repeats a string. Text methods (split, strip, replace) are in string methods and slice notation in slicing (in French).

Logical operations

Logical operators combine booleans, which will be used to write conditions.

  • and: true only if both sides are true.
  • or: true if at least one side is true.
  • not: inverts the value.
>>> True and False
False
>>> True or False
True
>>> not True
False
>>> 5 > 3 and 2 > 1
True

Comparisons (>, <, and == which tests equality) themselves produce booleans, which lets you combine them as in the last example.

Operator precedence

As in mathematics, Python evaluates multiplication before addition. Parentheses impose another order, and they are the most readable way to remove any doubt.

>>> 5 + 2 * 3
11
>>> (5 + 2) * 3
21

How do you make a Python script executable?

So far you have run your files with python3 hello.py. On Linux and macOS, you can run them like any other command, with ./hello.py. This takes a special first line, the shebang, and the execute permission. The shebang tells the system which interpreter to start. Here is a complete script, with a comment header:

#!/usr/bin/env python3
# Author: John Smith
# Date: 2026-10-14
# Description: prints a welcome message
print("Hello, World!")

The #!/usr/bin/env python3 line must be the very first in the file. /usr/bin/env finds python3 wherever it is installed. For Python it is only a comment, since it starts with #: only the system reads it. On RHEL 9, where python3 means 3.9, write #!/usr/bin/env python3.12. Save this script as my_script.py, then try to run it directly:

Terminal window
./my_script.py
bash: ./my_script.py: Permission denied

On zsh, the default shell of macOS, the same refusal reads zsh: permission denied: ./my_script.py. The file does not yet have the execute permission; chmod +x adds it (the principle of permissions is explained in Linux permissions):

Terminal window
chmod +x my_script.py
./my_script.py
Hello, World!

Without a shebang, or without chmod +x, there is still the safe method: python3 my_script.py, which always works. On Windows outside WSL, the shebang and chmod do not apply: run the script with py my_script.py.

How do you fix the most common errors?

An error is not a failure: Python tells you precisely what is wrong. When a program crashes, it displays a traceback, the list of lines it went through. The useful part is the last line: it gives the error type (NameError, TypeError…) then a message. Above it, it gives the file and the number of the faulty line. Always read from the bottom up: type, message, then line.

SymptomCauseFix
python: command not foundOn Debian, Ubuntu, RHEL or AlmaLinux, only the python3 command existsUse python3, or install python-is-python3 on Ubuntu
bash: ./my_script.py: Permission denied (on zsh: zsh: permission denied)The execute permission is missingchmod +x my_script.py, or run with python3 my_script.py
IndentationError: expected an indented blockThe line after if (or another block) is not indentedIndent by four spaces
NameError: name 'Name' is not definedCase mistake, or variable not created yetCheck the spelling and create the variable before using it
SyntaxError: invalid decimal literalA variable name starts with a digitRename it (attempt_2 rather than 2nd_attempt)
TypeError: can only concatenate str (not "int") to strA text and a number added togetherConvert with str() or int()
ValueError: invalid literal for int()int() receives a text that is not an integer, such as "12.5"Go through float() first, or fix the data
ZeroDivisionError: division by zeroDivision by zeroCheck the divisor before dividing

Put it into practice

A copied example teaches little; the 00 Intro Python exercise has you build a fondamentaux.py script step by step that reuses every notion of the lesson. It is in the python-training repository (the README is in French): clone it (or download it as a ZIP from GitHub), open the 00-Intro-Python directory and follow the README.md from step 1 to step 9, the complete script. Run the script after each step and read the errors instead of working around them. Allow about thirty minutes on top of the lesson.

The exercise prints its results with f-strings (f"Age: {age}" inserts the value of age into the text) and type(age).__name__, which gives the name of the type, int, without the <class '...'>; \n in a string inserts a line break. These three notations are only for display: copy them as they are; f-strings are covered in formatting a string (in French).

Stop before the "Challenge" section of the README: it asks for conditions and loops, which you have not seen yet. Come back to it after the lesson on control structures and collections (in French).

You have succeeded if, without rereading the lesson, you can:

  • create a script with a shebang and run it with ./, after chmod +x (on Windows outside WSL, with py fondamentaux.py);
  • comment your code with #;
  • create variables, display their type, and convert between int, float and str;
  • do calculations, work with strings and test and, or, not with comparisons, and predict the result of 5 + 2 * 3;
  • observe bool() on 1, 0, '' and 'Hello'.

The exercise does not trigger deliberate errors: if one of the errors in the previous table shows up while you work, you should be able to recognize and fix it.

Key takeaways

  • A program is run with python3 file.py (the python command does not always exist; py on Windows), with Python 3.11 or newer; the interactive python3 mode tests one instruction at a time.
  • Python delimits its blocks with indentation, not braces.
  • A variable is created by assignment, age = 30, without declaring a type. Names are case-sensitive (name and Name differ) and never start with a digit (2nd_attempt is rejected).
  • The four basic types are int, float (height = 1.75), str and bool; type() reveals them and int(), float(), str() convert (int("123") + 1 is 124).
  • / always returns a float, % gives the remainder (10 % 3 is 1), and multiplication comes before addition unless there are parentheses (5 + 2 * 3 is 11).
  • A string is indexed from 0: "Python"[0:3] is "Pyt".
  • # opens a comment, and the shebang #!/usr/bin/env python3 is one too for Python.
  • To run ./my_script.py, you need a shebang and the execute permission given by chmod +x.

Knowledge check

These questions cover only what this lesson teaches: variables, types, conversions, operations and running a script.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer