Concept: Funktionen und Code-Blöcke#
Functions and decorators#
Im letzten Kapitel wurde folgender Code verwendet:
@world.register
def on_setup(self):
world.fps = 1
world.speed = 3
In the second line, a function is defined that executes certain instructions (more on that later).
In the first line, this function is provided with a decorator. This decorator “attaches” the function to the World. Whenever the system wants to call the
world.on_setup
function, the function you defined is called. In this way, you can later define functions that respond to any events, such as keystrokes, …
Indentation und Code-Blöcke#
The third and fourth lines of the program code above are indented. This means that when called, the two indented lines will be executed.
Code blocks in Python always serve to define when a specific branch in your program begins and when it ends. Everything that is indented to the same level belongs to a common code block.
Coding-Standards Wie weit sollte eingerückt werden?#
The Python programming language itself does not define how far a code block should be indented, whether you use three, four, or five characters doesn’t matter - what matters is that all lines are indented equally.
In Python gibt es jedoch bestimmte Coding-Standards, auf die sich Programmierer geeinigt haben, damit der Code immer ähnlich aussieht.
It was agreed that code should always be indented by 4 characters. Of course, you can handle this differently for yourself - but at the latest when you work in a team, it is helpful to adhere to such conventions.
In Python, functions and conventions are defined in so-called PEPs (“Python Enhancement Proposal”). You can find style guides, for example, in PEP 8.
Besides indentation, you’ll find much more there, e.g., you write a = a + 3
instead of a=a+3
, because the former is easier to read. The programming language doesn’t force you to do so, but this way the code is easier for other programmers to read.
Many modern editors can assist you in writing clean code through auto-formatting and linting.