Skip to main content
Techlogia — AI and Web Development Berlin
All courses
Free to read – no sign-up

Python Basics

First steps with Python: print, variables, if/else, loop, function. Write 5 short scripts as .py files.

Duration: 30 minLevel: BeginnerExercises: 5

Your first Python scripts

Python basics: your first scripts

Python is one of the most-used programming languages — easy to read and ideal to start with. A script is a text file ending in .py that you run with python3 file.py.

Key terms

  • print(): outputs something to the screen.
  • Variable: a named storage slot for a value, e.g. name = "Max".
  • if/else: makes decisions depending on a condition.
  • for loop: repeats something for each element.
  • Function (def): a named, reusable block of code.

Work in the folder /home/student/python/ (mkdir -p /home/student/python). Edit files with nano, run with python3 file.py.

Your goal

You write five small scripts and learn the most important building blocks of any programming language.

Exercises

  1. 1. Hello world with print

    Concept: print(). The function print() displays text. Write a script that outputs "Hello World".

    mkdir -p /home/student/python
    echo 'print("Hello World")' > /home/student/python/hallo.py
    python3 /home/student/python/hallo.py

    Check: hallo.py contains a print(...) call.

  2. 2. Variable + print

    Concept: variable. A variable stores a value under a name. Create a variable and print it with print().

    nano /home/student/python/variable.py

    Content:

    name = "Max"
    print(name)

    Check: variable.py contains an assignment (name = ...) and a print(name).

  3. 3. A decision with if/else

    Concept: if/else. With if you test a condition; else is the case when it does not hold. Important: the code inside if/else is indented (4 spaces).

    nano /home/student/python/entscheidung.py:

    age = 16
    if age >= 18:
        print("adult")
    else:
        print("minor")

    Check: entscheidung.py contains an if ...: with a matching else:.

  4. 4. A for loop

    Concept: for loop. A for loop repeats a block for each element of a sequence. range(5) produces the numbers 0–4.

    nano /home/student/python/schleife.py:

    for i in range(5):
        print(i)

    Check: schleife.py contains a for ... in ...: loop.

  5. 5. Your own function

    Concept: function (def). A function bundles code under a name so you can reuse it. It can take parameters.

    nano /home/student/python/funktion.py:

    def greeting(name):
        print("Hello " + name)
    
    greeting("Max")

    Check: funktion.py contains a function definition def name(parameter):.

Related courses

Now practice it yourself

Reading is good – doing is better. Start this course on a real Linux VM, right in your browser. A free account is all it takes.

Start for free

Lab content under CC BY 4.0 – free to use with attribution (© TechLogia).

How do you like this page?

Python Basics | Techlogia Lab