Python Basics
First steps with Python: print, variables, if/else, loop, function. Write 5 short scripts as .py files.
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.forloop: 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 withnano, run withpython3 file.py.
Your goal
You write five small scripts and learn the most important building blocks of any programming language.
Exercises
1. Hello world with print
Concept:
print(). The functionprint()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.pyCheck:
hallo.pycontains aprint(...)call.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.pyContent:
name = "Max" print(name)Check:
variable.pycontains an assignment (name = ...) and aprint(name).3. A decision with if/else
Concept:
if/else. Withifyou test a condition;elseis the case when it does not hold. Important: the code insideif/elseis indented (4 spaces).nano /home/student/python/entscheidung.py:age = 16 if age >= 18: print("adult") else: print("minor")Check:
entscheidung.pycontains anif ...:with a matchingelse:.4. A for loop
Concept:
forloop. Aforloop 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.pycontains afor ... in ...:loop.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.pycontains a function definitiondef 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 freeLab content under CC BY 4.0 – free to use with attribution (© TechLogia).
