Python Basics
Basics
Python is used as the primary programming language for the DSP section of ringbuffer.org. Although there are various online resources for learning Python, this chapter introduces the most important aspects.
For further reading: as
Syntax
No Termination
Unlike many other languages, python does not require semicolons to terminate statements:
Indents
In Python, code indents are a part of the syntax. This is a very important and unique feature of python. This will become more important when using loops and conditions, as indatation can have an effect on the outcome of the code.
Code blocks always need to have the same indatation level. When using wrong indents:
the interpreter will give the following error message:
IndentationError: unexpected indent
Importing Modules
In Python, modules can be imported to extend the functionality. This is the equivalent to including libraries in other programming languages. Modules can be imported at any point in a script, before they are needed, but it is commom to import all modules at the beginning. After import, functions from a module can be called with the dot syntax:
It is common to import modules with shorter aliases for shorter code. Standard modules have typical aliases, that are used throughout the community:
If only a specific part of a module is needed, it can be imported exclusively with an alias to make it lightweight and fast:
Data Types
Strings
Lists
The list is Python's default, builtin data type to store collections of data. Lists are ordered, mutable and can combine different data types. Elements of lists can be accessed with brackets.
Arrays
Control Structures
Loops
Conditions
Writing Functions
Functions are defined using the def keyword. Arguments are declared in the parenthesis after the function's name. Return values are specified by the return keyword. Multiple values can be returned if comma separated. Note the indent to mark the function's body.
Since python code is not compiled but interpreted, functions need to be defined before they can be called:
Namespaces
All variables defined at the main level of the program (not in a function or class) are stored in the Global Namespace as global variables. All gobal variable can be listed as follows:
Every function creates a new namespace while being executed - see the LEGB rule.