Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

June 10, 2026

Matching game in python

The font-name needs to be adjusted according to the operating system, otherwise only a question mark is shown in the window.

import pygame
import sys
import time

# Pygame initialisieren
pygame.init()

# Fenstergröße
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Emoji-Text-Matching")

# Farben
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)

# Schriftarten (mit Unicode-Unterstützung)
# font_large = pygame.font.SysFont("Segoe UI Emoji", 120)  # Für Emoji Windows
font_large = pygame.font.SysFont("Noto Color Emoji", 150)  # Für Emoji Linux
font_small = pygame.font.SysFont("Arial", 30)            # Für Text

# Emoji-Text-Paare (20 Einträge)
pairs = [
    ("🐶", "Hund"),
    ("🐱", "Katze"),
    ("🐭", "Maus"),
    ("🐹", "Hamster"),
    ("🐰", "Hase"),
    ("🦊", "Fuchs"),
    ("🐻", "Bär"),
    ("🐼", "Panda"),
    ("🐨", "Koala"),
    ("🐯", "Tiger"),
    ("🦁", "Löwe"),
    ("🐮", "Kuh"),
    ("🐷", "Schwein"),
    ("🐸", "Frosch"),
    ("🐵", "Affe"),
    ("🐒", "Affe2"),
    ("🐺", "Wolf"),
    ("🐗", "Wildschwein"),
    ("🦊", "Fuchs"),
    ("🐝", "Biene"),
    ("🐛", "Raupe"),
    ("🔪", "Messer"),
    ("🔦", "Taschenlampe"),
    
    
]

# Position für Emoji und Text (zentriert)
emoji_x, emoji_y = WIDTH // 2, HEIGHT // 3
text_x, text_y = WIDTH // 2, emoji_y + 150

# Hauptspielschleife
def main():
    clock = pygame.time.Clock()
    running = True
    current_pair_index = 0

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # Hintergrund
        screen.fill(WHITE)

        # Aktuelles Paar anzeigen
        if current_pair_index < len(pairs):
            emoji, text = pairs[current_pair_index]

            # Emoji groß anzeigen
            emoji_surface = font_large.render(emoji, True, BLACK)
            emoji_rect = emoji_surface.get_rect(center=(emoji_x, emoji_y))
            screen.blit(emoji_surface, emoji_rect)

            # Text darunter
            text_surface = font_small.render(text, True, BLUE)
            text_rect = text_surface.get_rect(center=(text_x, text_y))
            screen.blit(text_surface, text_rect)

            # Nächstes Paar nach 1 Sekunde
            time.sleep(1)
            current_pair_index += 1
        else:
            # Alle Paare gezeigt: Beenden oder neu starten
            font_done = pygame.font.SysFont("Arial", 40)
            done_text = font_done.render("Alle Paare gezeigt!", True, BLACK)
            done_rect = done_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
            screen.blit(done_text, done_rect)

        # Aktualisieren des Displays
        pygame.display.flip()
        clock.tick(30)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()

December 24, 2025

Python for event detection of a warehouse robot

 The Python programming language is recognized as a high level language which allows to program complex software in a low amount of code. The reason is, that python has many builtin libraries and has an easy to understand syntax for parse. Its much easier to create a prototype in Python than in other programming languages like C or Assembly.

Unfurtunately, the Python language remains a classical imperative language which means, that the programmer has to define functions, classes and variables. This formal syntax ensures, that a computer can execute the statements. To increase the abstraction level further another syntax is needed which is presented next. The goal is to program an event recognition system for a warehouse robot. Instead of implementing a GUI prototype the goal is to write only a list of [tags] which can be detected by the robot. The tags are described in a python dictionary:

warehouse_robot_taxonomy = {
    # --- Navigation & Localization ---
    "NAV_WAYPOINT_REACHED": "Robot base has arrived at the specific coordinate destination.",
    "NAV_PATH_OBSTRUCTED": "LIDAR/Depth sensors detect an unexpected object in the path.",
    "NAV_RELOCALIZATION_REQ": "Robot uncertainty in pose exceeds threshold; seeking landmarks.",
    "NAV_FLOOR_HAZARD": "Detection of liquid spills, debris, or uneven surfaces.",

    # --- Manipulation & Payload ---
    "MAN_SHELF_ALIGNED": "End-effector is centered and parallel to the targeted rack slot.",
    "MAN_GRIP_SUCCESS": "Tactile/Force sensors confirm object acquisition.",
    "MAN_GRIP_SLIP": "Loss of contact or shifting weight detected during transport.",
    "MAN_LOAD_SHIFT": "Internal IMU detects payload instability while the robot is moving.",

    # --- Perception & Identification ---
    "PRC_SKU_VALIDATED": "Barcode, QR code, or RFID successfully read and matched to manifest.",
    "PRC_MISPLACED_ITEM": "Vision system identifies an object where the database expects a void.",
    "PRC_SHELF_FULL": "The destination bin has no available volume for placement.",

    # --- Safety & Human-Robot Interaction ---
    "SAF_ESTOP_ACTIVE": "Physical or software-based emergency stop has been engaged.",
    "SAF_HUMAN_NEAR": "Safety scanners detect a human worker within the 'Slowdown' zone.",
    "SAF_COLLISION_IMMINENT": "Time-to-collision calculation triggers immediate braking.",

    # --- System & Maintenance ---
    "SYS_BATTERY_LOW": "Charge level requires return to docking station.",
    "SYS_COMMS_LOST": "Loss of heartbeat or high latency with the Warehouse Management System (WMS)."
}


Such a list of tags has not much in common with a software project, but its similar to a database. The table stores two columns: name, description. The dictionry stores the items in the table.

The idea behind the project is, to annotate the sensory perception with one of the tags. For example, if the battery is low the tag [SYS_BATTERY_LOW] gets activated or if the robot has scanned an object the tag [PRC_SKU_VALIDATED] gets activated. The entire game state is projected towards a tag vector with 16 entries, each of the tags can be true or false so the game state is encoded in 16 bits, which is a very compact representation. The python dictionary ensures, that the human operator has a better understanding of each of the tags. There is a name plus a descripotion given.

December 17, 2022

Comparing C#, Java and Python

 

All the three lanuages were creaed with attempt to replace the C++ language. It is much easier to write an application with C# and similar languages because no pointers are needed, and there is a large amount of libraries. All of these languages have cons and pros. Let us start with the C# language which has become famous in the Windows community.
C# is the default language in a windows operating system and can be compiled without additional software. The language standard is similar to Java but the syntax is easier to learn and much better documented. The big disadvantage of C# is, that it is not available for Linux. The existing mono ecosystem has to be called a joke because it can't run major components like WPF (GUI widgets) and ADO.net (database access). That means most of the C# programs won't run in Linux. It is pretty hard to create a C# app which runs in windows and Linux as well.
In contrast the java language was created for cross compatibility in mind. The runtime environment in Linux and Windows is the same Similar to C# lots of documentation is available and Java is a mature language. The only problem with java is, that it has never replaced C/C++ because Java programs are known as slow and poorly programmed. For internal projects java is used sometimes.
The third language is Python which has become a surprisingly successful language. Python was started as a scripting language which is around 20x slower than C/C++ code. On the other hand it is very easy to write a software in python and it will run on all major operating systems.
It is hard to say what of these languages is the best one. Perhaps none of them. C# won't run in Linux, Python is too slow, and java can't replace C++. The good news is, that with all these languages it is easy to write software. Even complex programs like games can be created in a few hundred lines of code. It should be mentioned that for unknown reasons none of the presented languages has replaced c/c++. If C and C++ is seen as the same language, more than 80% of the production ready code for windows and Linux is written in the language. In contrast, a language like Java is seen as a toy language without practical value.
From an abstract point of view, it is not possible to invent a pointer free language and use this language for practical application. It seems, that pointer oriented programming is the only way for writing production ready applications. Pointer-oriented means that the abstraction level is lower and the programmer has to decide in detail how to store data in the main memory.

October 21, 2022

Modular programming with python

 

Sometimes it was asked how to implement object oriented programming in low level languages like C and assembly. A possible idea would be to improve the existing struct datatype with functions which are pointers. Then the user has to allocate memory and can use objects in C. But the overall pipeline is very complicated and there is an option available to simplify the idea drastically.
The idea is to dismiss object oriented programming at all and prefer modular programming. Modular programming is a complexity reduction technique which is available in most existing programming languages. It can be used in python and in C and pascal as well. The idea is that a single file is equal to a module. [1] The file contains of variables and functions and comes close to the concept of a class. in the written sourcecode a program written with modules and one with classes are looking nearly the same. A module allows to group items in the sourcecode into cluster and maintain the code separately.
Most object oriented programs are in reality normal modules distributed over many files. The only reason why OOP is the dominant programming paradigm and modular programming has become a niche is because of the existing programming tutorials. The self understanding of most books is, that a programming language consists of statements and functions and this enough to solve a problem. The problem is, that without classes aka modules it is impossible to solve larger problems. If the code is longer than 500 lines of code there is a clear need to split it into sub entities. Unfortunately this strategy is not implemented directly in a programming language but it has to do with project management and compiler preprocessors. It can be s
From the perspective of modular programming it is surprising to see, how similar programming works in different languages. In contrast to a common myth the programming languages Pascal, Python, C++, C and , Assembly and Forth have one thing in common. They are supporting all the concept of units. A unit is – again – a single file which can be included in other files and allows to split the code into logical groups. Similar to OOP it allows to group variables and methods into the same instance.
To understand why modular programming is not very common it is important to take a look back into the didactic of programming. In the 1980s the concept of structured programming was mentioned frequently. Structured programming means to divide the sourcecode into functions which can be realized with C and pascal. Advantage is, that each function can be maintained separately which allows to writer longer programs. What was ignored in the 1980s is, that structured programming alone is useless because if a file contains of around 10 functions it will become hard to maintain anymore. So the limit is, around 500 lines of code which can be managed with structured programming alone.
In the 1990s the concept of object orientation was promoted as the logical next step after structured programming. The idea was to encapsulate the code in object libraries which allows an unlimited code size. Nobody has questioned the idea at all or compared it with modular programming which provides a similar feature.
In theory, OOP is superior over normal modular programming. But in the reality, most programs won't profit from these additional advantages. Nearly all projects which are smaller than 100k lines of code can be realized with modular programming very well.
[1] https://python-course.eu/python-tutorial/modules-and-modular-programming.php

September 06, 2022

Creating a minimal outliner in Linux

 



For creating a 1dArrayoutliner a first mockup is available.It was realized in 200 lines of code in the python language and shows the main window for an outliner. It is using a two pane layout. The user can select in the left menu the page and will see in the right pane the content of a page.
The page content is rendered with a self written parser. A pushdown automaton analyzes a markdown file and translates it into a rich text window. Right now, the GUI framework is wxpython but it seems that it is not powerful enough. So perhaps it makes sense to switch to tkinter?
The bottleneck of the current project is to save the information from the text editor into a markdown file. To realize it the text editor needs the abilty to save something as markdown, or the program needs to parse the information in the window manual. The task is needed because images and text are shown at the same time in the window.
That means, writing a text only outlier program is pretty easy, but if the images are shown inside th text it is much harder to program it.
 
Perhaps it makes sense to explain why there is need to program yet another outline editor. Because most of the programs from the past are very big projects It seems, that the average outliner / PKM software has at least a size of 1 MB and there is no upper limit so that current software has 200 MB and more.
The idea is to reduce the requirement to a minimum and write a much smaller outliner program which has 100 kb and less. For doing so there is need to specifiy which features should be implemented and which not. From a database persective an outliner has to implement the CRUD operations which stands for create, retrieve, update and delete. The interesting situation is, that more actions are not needed, if the user can add new pages and modify the existing he is happy. Editing a page means usually to enter text in the richt text window which includes adding images. I think it is not possible to ignore images and assume that a text only outliner will fulfill the needs of a user.
 

August 10, 2022

High level programming language

 

The pygame library is for sure a high level programming language. It would be interesting to know the reason why this is the case. The working thesis is, that it has to do with amount of commands which are provided.
The exact number can be determined with the official API description.[1] The amount of all commands in the pygame 2.0 library is 754 which is a lot. Every command has parameters and is described in the API. Creating such a library and writing the documentation takes a lot of time. In addition it is important to know that most python applications will need more than a single library. They include other libraries which have the same and more complexity.
From a user's perspective a complex large library is easier to use than a simple one. A game library which has fewer than 20 commands is much harder to use, because the user is asked to create many commands from scratch. In contrast, the pygame library provides many useful tools out of the box. There is a single command to initialize the graphics screen, another commands draws a line, and a third command create a timed loop with 60fps.
Let us compare pygame with low level programming like Assembly and very important with Forth. The assembly language has a low amount of commands. Forth has reduced the instruction set further. Most forth implementation have no additional libraries but the amount of commands is reduced to fewer than 50. The user is asked to write with only 50 commands useful programs. Technically this is possible, but it is a demanding task.
We can only guess how many commands are provided by a python environment. Perhaps the amount of all commands is 10k or even more. What we can say for sure is, that all the libraries combined have a huge documentation with thousands of high level commands. This ecosystem makes it easy to create high level applications like games and GUI applications in a few lines of code.
Other high level languages like Java and C# are working with the same paradigm. The amount of commands in the typical Java library is endless. Some programmers have written these APIs in the past. They have done so because it simplifies the programming. Today's scripting languages are the most high level languages available The disadvantage is, that such an ecosystem can't be created easily. It is possible for a single programmer to write a Forth environment but writing a python ecosystem which includes some important libraries is impossible for a single programmer.
In some older tutorials from 1980s it was assumed that Forth is a low level and a high level language at the same time. This assumption is wrong. Forth is a low level language and nothing else. In Forth there is no large library available and also a standard amount of commands is missing. The typical forth interpreter provides very few commands. This is an obvious sign, that it is located on the low level layer. The factor language which is forth dialect, is working with a different objector. Factor has similar to Python a large library with predefined commands which makes it easy to write applications. But, Factor is not a typical Forth implementation because it is not minimalist. The question is not about sequence of commands which are stack based but the more serous question is about the size of the library with predefined commands.
[1] https://devdocs.io/pygame/

November 04, 2021

Modular programming with python – a tutorial for creating a game

Writing with python a small is not very complicated. The existing pygame library allows even newbies in doing so. Most tutorials are assuming that the game is created with the object oriented paradigm That means there are classes for the GUI, for the physics and for the main program. This assumption makes sense because since the advent of the C++ and C# language nearly all games are created this way.
A seldom mentioned technique for creating larger software programs was invented before tor the advent of C++. What was used before is called modular programming and can be realized with python as well. The interesting situation is that modular programs allows similar to OOP to divide a larger project into chunks which are created individual. First thing to do is to create the physics module which contains of a single file.

The formatting has similarity to a class but the class statement is missing. The next step is to create the main module which has also no classes but a variable for drawing the window and two methods. The interesting situation is that the physics module is not initiated as an object but it was only importad and then the main module is sending messages to it.


The game itself consists of a small circle on the screen which can be moved with cursor arrows left and right.


November 02, 2021

What Python can learn from C

 

The Python language has become famous because of its object oriented features. This was the main improvement over previous scripting languages like Perl. On the other hand Python has a seldom described features which can be used as a replacement to classes. The concept of a module is to put all the functions in a single file and include this file somewhere else.
Somebody may argue, that a class should be stored in a file and including a module is equal to include a class. The situation is more complicated. Because modules can be used without classes. This programming style is what c programmers are doing: they are creating modules in which the scope of variables and functions is limited and then the module gets included into the main program.
Apart from modules Python support also packages. A package is a directory which contains of many modules. This allows to create larger programs and very important they can be converted easily into c code. That means the original Python program doesn't use classes there for the similarity with plain C is bigger.
The real problem in programming is not to learn a certain language but the problem has how to write programs which are larger than 100 lines of code. The amount of 100 LoC fits well into a single file. It is equal to define a small number of variables and apply 4-5 functions to them. The problem is that real programs will need much more code lines and hundreds of functions. Organizing them into a single file is technically possible but it will become unlikely that the programmer is able to maintain such a file. Object oriented programming provides one possible answer to this problem, but modular programming has also an answer.
Let us describe how to write a module in Python without using classes. The idea is to create a new file and import this file in the main program. The new file contains of variables similar to class variables and methods which can modify these variables. Some of the functions can be accessed from the outside so that the module communicates with the main program. In contrast to the C language the workflow was simplified drastically, there is no need to create dedicated header files and the program will run without a compilation step.

October 27, 2021

Comparison between python and C++

 

There are two important programming languages available which are python and C++. The first one can be programmed much easier but the code is running slow. Python programs in general are around 30x slower than the C++ counter part. The additional problem is that code written in python can't be deployed because the python runtime engine is needed.
On the other hand, C++ is the defacto standard for writing low and high level software. The interesting situation is that both languages are used by today's programmers because they are fulfilling different needs. C++ is an example for a classical programming language. There is need to learn the language first, use a complicated IDE and take care of datatypes, pointers and object oriented features. In contrast to previous languages like pascal or C the C++ standard has simplified programming and can be used to create graphical applications If someone line to create a paint application or to write a game then the C++ language is a here to stay.
But if C++ is the number one language for creating applications and games as well what is the idea of python? The idea behind python is that there is no need for programming but what is created instead is a script. A script is a visual basic like macro which automates something. It doesn't make sense to package a script into a program nor to upload it into the internet, but scripts are locally run modifications to existing software similar to creating an excel spreadsheet. So python is not a programming language but a scripting language.
Basically spoken if someone likes automate something but has no time to write source code than the python language is a here to stay.
Python and C++ are providing a certain perspective. C++ is a language which is oriented on the needs of a computer. Similar to Assembly language or C, C++ makes it easier for a human to communicate with a computer. The programmer doesn't need to know opcodes in hexadecimal notation but he can write down function names and datatypes. With this assumption it is pretty easy to write software.
On the other hand, python is oriented on a problem. It supports problem solving and things like datatypes and pointers are not needed. The interesting situation is that python isn't able to replace c++. Even if python is the more recent approach for programming, python has created many unsolved problems. That means python is only an additional language over C++.
Let us try to criticize C++ a bit. Suppose a programmer has no need for fast running software and he has no need to deploy the code in a production environment. Under such constraints, there is no need to use C++ anymore. The reason why Python has become a wide spread language is because of changing demands. Running a software very fast was only important until the 1990 in which computer power was limited. And deploying production ready code is only needed, if the code should be used a larger audience.
This allows to imagine what the purpose behind Python is. Python is used on fast modern computers in which performance is no longer problem. And it is used to implement prototype software.

October 26, 2021

Introduction into object oriented programming

 

Before the powerful OOP style can be explained there is need to take a step back and analyze how programs were created before the invention of Object oriented programming. The idea was that there functions which are accept a parameter and then the function returns something to the main program. The sourcecode for a simple calculator app is shown.
# without class
def init(mylist):
  mylist=[2,4,6]
  return mylist
def add(mylist):
  result=sum(mylist)
  return result
def avg(mylist):
  result=add(mylist)/len(mylist)
  return result
  
def main():
  a=[]
  a=init(a)
  s=add(a)
  av=avg(a)
  print(a,s,av)

main()
Each of the three functions take a list as input and returns a value or a list as output. The idea is the main program communicates with the subfunctions with the help of the parameter.
In the example only a single parameter was used but the concept can be extended so that the function header take 5 and more parameters as input. It is not very hard to guess that this programming style works technically great but it is hard to read. The alternative is object oriented programming. OOP means that no parameters have to be send to the function but the function knows in advance which variables are needed.
The resulting oop syntax is very easy to read and it contains mostly of a statements like “object.dosomething()”. All the needed parameters are stored in the object already as class variables.
Somebody may argue that the different notation wouldn't result into a faster binary code. And he is right, OOP is mainly something for the programmer but not for the computer. In most cases OOP oriented compilers are harder to create and will produce slower binary code. But the technique allows to create larger programs.
Even if the OOP has felt a bit out of fashion since the 1990s it remains the leading programming paradigm. Most of code is written in this style and even C code was rewritten in an OOP style. It is a very influential programming style. From a historical perspective OOP were introduced in the mid 1990s to the main stream programmer. In that period most of modern OOP languages like java, C++ and python were created. It is very difficult to find a larger project which is not using the OOP programming style.
The interesting point is that the OOP concept can be extended drasticaly. It is possible to store in an object another object. This allows to increase the amount of codelines further. At the end the program wil need 10k and more lines of code which is occupied by lots of classes. From a technical perspective such a program is not very hard to hard to compile or to execute. A program which has 10k lines of code fits into 400 kilobyte of disc space. The resulting binary file will need also around 400 kb of RAM. Compared to the average RAM of a computer this is very little amount of space. But creating all these codelies takes a long time. A single programmer will need many months until the program was created.

July 11, 2021

Dictionary in C++ and in Python in comparison

The C++ version is faster, of course.

map.py
#########
d={
  "A":{"one":0, "two":0, "three": 0,},
  "B":{"one":0, "two":0, "three": 0,},
}
for i in range(20000000):
  d["A"]["two"]=5
  a=d["A"]["two"]
  #print(a)

map.cpp
###########
#include <iostream>
#include <map>
#include <string>
#include <string_view>
// g++ -O3 -std=c++2a map.cpp
 
int main()
{
    std::map<std::string, std::map<std::string, int>> d;
    d["A"]["one"]=0;
    d["A"]["two"]=0;
    d["A"]["three"]=0;
    d["B"]["one"]=0;
    d["B"]["two"]=0;
    d["B"]["three"]=0;

    for (int i=0;i<20000000;i++) {
      d["A"]["two"]=5;
      int a=d["A"]["two"];
      //std::cout<<a<<"\n";
    }
}

July 10, 2021

Simpler programming with groovy and python

The programming community consists of two opposing group. The first one are old school programmer who have learned programming in the 1980. This group is familiar with Assembly language, C and sometimes the C++ language is used for creating modern desktop applications. This approach to writing software can be called a professional one because it garantees the maximum performance and is used to create large scale productive programs.

On the other hand, there are programmers who are not calling themself developers because they have never learnt to write code in C or Assembly language. The difference between both groups can be made visible by the different understanding of a pointer. Only the real programmers can explain what a pointer is, and they have used them all the time. Pointers are used for creating faster games and handle lot of data in a program.

The interesting situation is, that it is not possible to learn C/C++ or assembly without understanding pointers. They are a fundamental part of these language. To write anyhow a program a different sort of programming language is used. Typical examples for recent programming languages are groovy, python, matlab, javascript and Autoit. What these languages have in common the user has to enter only a little amount of code, and the written code reads easier.

A typical example is to compare a swing gui written in java, with a GTK+ gui written in C. The c code needs 4x more lines of code, and ofcourse the pointer operator * is used everwhere. In contrast, Groovy and especially python are much easier to read.

There is a reason why the scripting languages haven't replace real programming languages. Because a scripting language is using a lot overhead to reach the same goal. They are not a minimalist language like Assembly, but before groovy can be executed lots of programs have to installed first. And all of the underlying programs like operating systems, Virtual machines are written not in groovy but in powerful languages like C, C++ and Java.

June 11, 2021

Warum größere Projekte in Python keinen Sinn machen

2017-10-04 C++, import from other blog

Von den Sprachstandards her ist Python ausgezeichnet um größere Projekte darin zu realisieren. Die Python Virtual Machine ist hinreichend robust, die Python-internen Möglichkeiten zur objektorientierten Programmierung sind vorbildlich und das Modulkonzept erlaubt es Klassen zu Packages zu aggregieren. Technisch gesehen kann man mit Python durchaus Projekte mit 100k LoC oder sogar noch mehr realisieren. Es gibt nur ein Problem: wer möchte diese Programme verwenden? Endanwender machen üblicherweise einen großen Bogen um GUI Applikationen die in Python erstellt wurden, und Systemprogrammierer werden garantiert keine Libraries einbinden, die in Python geschrieben wurden. Dagegen spricht schon die geringe Performance. Python erinnert an das Schicksal was Turbo Pascal ereilt hat: es ist eine Lehrsprache in der Programmierausbildung, kann aber nicht für reale Projekte eingesetzt werden.

Die Sprache als solche ist vorbildlich: Python ist sehr elegant designt. Und es lässt sich darin auch produktiver Sourcecode schreiben, in dem Sinne dass man für einfache Aufgaben wie das Sortieren eines Arrays eben nicht erst tagelang in Foren um Rat fragen muss, sondern einfach den pythonic way of life verwendet. Nur, stellen wir uns mal vor wie das in der Realität konkret aussieht. Man schreibt sein elegantes Python Programm runter, es besteht aus 12000 Lines of Code, nutzt dafür selbstverständlich mehrere Klassen und dann? Rein theoretisch ist das Script jetzt überall ausführbar, aber wer will das auf seiner Maschine tatsächlich verwenden? Das Problem mit Python ist, dass es nur eine weitere Programmiersprache ist in einer ganz speziellen Nische (anfängerfreundlich und interpretiert) und das der damit erstellte Code garantiert nicht in größere Projekte wird einfließen. Genau genommen kann man Python Programmierer nur bemitleiden, weil ihre schönen Programme sonst keiner haben will. Java Programmierer werden ganz sicher keine Python Bibliothek in ihr Projekt einbinden, C Programmierer auch nicht. Mit etwas Glück kann man die Library im Pypi Repository unterbringen, aber das wars dann auch schon. Es ist keineswegs Zufall dass es keine großen namenhafte Python Projekte gibt, mit mehr als 10k LoC. Wie gesagt, rein technisch geht das ausgezeichnet, nur leider ist die Welt außerhalb von Python sehr viel kritischer in solchen Dingen.

Ich bin mir nicht sicher, ob Guido van Rossum der Welt einen Gefallen getan hat, als er die Sprache erfunden hat. Auf den ersten Blick hat Python viele Vorteile. So richtet es sich nicht explizit an Informatiker sondern an Wissenschaftler aus den Bereichen Physik, Linguistik und Geschichtswissenschaften. Ferner ist als interpretierte Sprache mit kurzen Edit-Compile-Run Zyklen konzipiert wodurch man in kurzer Zeit viel Code schreiben kann. Genau genommen ist Python also in eine Lücke vorgestoßen wofür es davor noch keine Sprache gab. Aber kann es wirklich das Ziel sein, zu den gefühlten 500 Programmiersprachen immer weitere hinzuzufügen um darüber die Spaltung der Entwickler voranzutreiben? Reicht es noch nicht, wenn Java und C# Programmierer gegeneinander arbeiten? Braucht man neben PHP, go und Perl noch weitere Sprachen? Python hat sogar das seltene Kunststück fertiggebracht zu sich selber inkompitbel zu sein. Bekanntlich laufen Python3 Programme nicht mehr auf einem Python2 Interpreter. Und das Pypy Projekt ist zwar ein JIT Compiler kann aber nicht alle Bibliotheken aus cpython verarbeiten. Irgendwie ist Python eine ganz eigene Welt die im universitären Umfeld prächtig gedeiht und die dazu führt, dass Leute ihre Zeit verschwenden. Anders kann man es nicht ausdrücken, wenn man Ressourcen in den Aufbau von Python Sourcecode investiert.

BEISPIEL
An einem kleinen Beispiel möchte ich das Thema vertiefen. Früher habe ich schön mit pygame Spiele programmiert. Das geht wunderbar einfach, und mit erstaunlich wenig Sourcecode. Man fängt einfach oben an mit “import pygame”, aktiviert das Fenster, und schon kann man seine erste Box auf den Bildschirm zaubern. Jetzt wo ich nicht pygame nutze, sondern in C++ mit SFML das Spiel realisiere ist es deutlich aufwendiger. Man muss sich durch Manuals auf English wühlen, es gibt für alles mindestens 4 Möglichkeiten und mehr Sourcecode benötigt man auch. Für den Computer macht es keinen Unterschied. In beiden Fällen sieht man eine GUI in der etwas angezeigt wird, und beidesmal mit ruckelfreien 60fps. Der Unterschied liegt in der Community die hinter der Sprache steht. Projekt-1 wendet sich an die Python Community, also an Nicht-Informatiker, während Projekt-2 sich an C++ Programmierer richtet. Die Community unterscheiden sich im Anspruch an sich selbst. C++ Programmieren tönen lautstark dass sie die besten Programmierer der Welt seien und demzufolge haben sie auch den Ehrgeiz die besten Programme des Universums zu schreiben, während es in der Python Community sehr viel entspannter zugeht, in dem Sinne dass man sich gegenseitig versichert Anfänger zu sein und überhaupt sich eher mit mit inhaltlichen Dingen und weniger mit Programmieren beschäftigt. Damals in Python war meine Produktivität immerhin bei stolzen 10 Zeilen Code am Tag, jetzt mit C++ in SFML ist sie abgesunken auf 5 Zeilen täglich. Dadurch verdoppelt sich natürlich die Zeitdauer bis das Projekt fertig ist.

March 22, 2020

The biggest strength of Python is it's slowness

If a newbie tries out the Python interpreter for the first time, he will notice that the code runs horrible slow. Compared to the compiled C language a python program is around 20x slower which makes the language unusable for practical application. And exactly for this reason Python is a great language. Because it draws a line between teaching and productive scenario.

From a technical point of view, it's not very hard to make Python faster. One option is to optimize the python interpreter or develop a just in time compiler. The resulting language would have much in common with node.js, java and C++. It will become a language which is used for teaching programming and for programming real systems at the same time.

The good news is, that this is not the goal of Python. It's a teaching language. It allows to learn programming and create prototypes but the Python ecosystem prevents that Python code gets executed in real operating systems. Let us compare Python with other object oriented languages:

Java, C++, C#, node.js and ruby have in common that they are used for teaching programming to the newbies. Java for example is widely used in an academic context. It explains very well what object oriented programming is. The fast executation speed is that main difference of Java to Python. A fast execution speed implies that the language can be used outside a learning environment as an alternative to C.

Is Java able to replace C programs? No it doesn't. C is the number one language in the wild. It's used for creating operating systems, libraries, AAA game and object-oriented desktop application. The only problem with C is, that it's not used for teaching programming, because it has no explicit classes. And exactly this gap was filled by Python. Python is the missing part to train the newbies. If somebody has understand who to write Python programs he can try to use C structs and C pointers for doing the same for writing production ready code.

Python -> C -> Forth

Python is the number one language for creating prototypes and learn to program. The entry barrier for creating python scripts is very low. Even non programmer can create a hello world application within minutes. The C language is the number language for creating software in the wild. Most (>80%) softwareprojects in the reality are realized in C and it's superior to C++, Java and C#. C is the dominant language for the x86 PC architecture and any sort of application can be created. The Forth language is a special case, it's a language for programmers who are already with C and who are searching for a faster alternative. The main difference is that Forth will run on non-x86 systems which can be designed in FPGAs from scratch. Rewritting existing C code into Forth is good startin point to get familiar with stack-based computing.

Educational programming languages

Recent object oriented languages like Java and C# are teached very often in computer courses as an example for object oriented programming. The audience are newbies and non-programmers who are interested in learning the language from scratch. Python can be teached also in such courses. The main difference between Python and Java is, that Python programmers are aware that their language can't be used for practical applications. If they are writing a small prime number generator with a for loop they will recognize very soon, that the language is way to slow for practical applications. Python is an educational only language. That menas, if somebody like to program software in the wild he won't use Python.

In contrast the educational situation for Java is different. Java is used in introduction courses and the same Java language has become popular in writing real applications. Similar to C++, Java is used in an academic context and for practical applications at the same time. The problem is that programming experts are using C since 30 years and they are not planning to rewrite the code in any other language. That means, all the newly written Java, C++, Python and Ruby libraries are useless. Real operating systems are equipped with normal C libraries which are providing the maximum performance and are maintained by experts and any other language is critized as a toy language. In the case of Python, the Python community won't argue against it. They know, that Python can't replace a C library.

The situation in the programming world is, that there is the expert language C on the one hand which is used for creating important software, productive software and for large scale projects, and all the other languages were developed for niche problems, for academic purposes or as an alternative to C. A relative new understanding of computer programming is, that the C language is especially recommended for object oriented programming. This is a bit surprising, because C++, Java and C# were developed as a dedicated OOP language, but they have failed to replace C in this domain.

What the alternative languages over C have in common is, that they are widespread used in an educational setting. Many books were written about it and they are used in computer courses at the university. In contrast, the C language is never teached anyware and modern literature isn't available. The assumption of the newbies is, that the C language is outdated and is replaced by Java, C++ and other languages. This thesis isn't backuped by the percpetion in the reality. If software projects becomes larger, and are realzed with modern OOP technique it's in all cases a C only programming project. This is not wishful thinking but can be determined by take a look into the sourcecode of the software.

Why is C so popular? The reason is, that software engineering can't be separated from low level programming. If somebody likes to write a high level application he will need an operating system and existing libraries for doing so. To get access to the existing sourcecode, an API is needed and every API is working with pointers. Even higher languages like C++ and Java are using pointers all the time, and before the newbie is able to program in Java he has to know what pointers are. That means, it's not possible to ignore the topic at all.

And if C supports pointers, structs and modules out of the box, the programmer has no need to use a different langauge than the existing one. That means, especially newly written code is created in C. The prediction is, that this will be the same in 10 years from now, except somebody invents a language which can replace C.

The only area in which C can be ignored is for academic reasons and for software prototyping. If the idea is to explain in general what object oriented programming is, how an algorithm is working in theory and how to create an UML diagram, the C language isn't the best choice in doing so. A java based UML Generator is the prefered choice for software engineering teaching, while algorithm can be explained with Python very well. It makes no sense to print a screenshot of C sourcecode in a textbook because the syntax is hard to understand. C is way to low level and provides too much details of the underlying CPU.

February 08, 2020

Transition from Python to Javascript

Python is known as an easy to learn programming language which is available on all operating systems and has object oriented features available. Creating new software in Python isn't recommended because the Javascript language is the natural successor. It's also available under all operating systems, provides object oriented features and has two additional advantages:

1. GUI applications can be created much easier compared to Python. In python a GUI depends strongly on the underlying framework which is tkinter, python-gtk or Python under Windows

2. the execution speed is faster, which makes Javascript the prefered choice for productive sourcecode which can't be realized with Python program

Sure, Python is used by many programmers, but the latest version which is Python3 can't compete with Javascript and node.js. What we can say about the Javascript language is, that it's not only used for prototyping new applications, but Javascript results into working code. In contrast, a program written in Python needs to be converted into faster programming language which is C++, Java or C#. This additional step isn't needed for Javascript which runs great in the normal Javascript interpreter.

Another interesting aspect is the node.js runtime environment. It's possible to configure the engine so that it's integrated in the programming IDE. The user types in the sourcecode not into a webbrowser but with a normal IDE, and after press on the run button, the status box will show the result. This allows a fast edit-compile-run cycle. It's basically the same workflow like programming code in Python. The only thing what is different is, that missing tab spaces.

January 25, 2020

Node.js for Python programmers



The main reason, why Python has a large amount of users is because it combines a prototyping language with object oriented programming. Similar to C++ and Java the user can create objects and classes which allows to realize more advanced projects compared to purely procedural programs. On the other hand, Python is more easily to learn than C++ because the syntax is a high level one. The combination of both feature explains most of today's widespread usage of the Python language.

What many people doesn't know is, that node.js and Javascript is the better Python. Similar to Python it can be used as a prototyping language. An easy example is the canvas element in HTML which allows to program graphics and even graphics animation. At the same time, Javascript is capable of object-oriented programming which allows to create large scale apps. It's main advantage over Python is, that the underlying virtual machine is really fast. It outperforms Python easily.

It's not very hard to predict, that Javascript will become the most successful language which will get used by more users than Python, PHP and Java combined. The only language which can't replaced by Javascript is Forth. Forth is a different language which is more powerful than Javascript but more complicated to learn. The reason is, that Forth can be realized on different machine architecture and provides it's own operating system. This is not possible with Javascript.

The reason why Python but not Javascript is widespread used in the year 2020 has historical reasons. Javascript and especially node.js are very young projects. The 1.0 version of node.js was released in 2010 and most programmers have decided to ignore it because they are familiar with classical back end language like C++, Java or Ruby. The comparison between classical language was focused on the question if compiled or modern scripting languages are the prefered choice. C++ programmers are convinced that only compiled languages are providing the maximum performance, while Python developers emphasize the advantages of an interpreted easy to learn language. The discussion about the pros and cons was easily because both paradigm had clear features. Python is a slow language, but can be written fast. While C++ is complicated to learn but can be executed fast.

The node.js framework is something which outperforms both languages. It's easier to program than C++ and it's faster then Python. This makes node.js the perfect choice for all applications. Additionally it runs under all operating systems, can be used for backend and frontend development, supports object oriented programming and has a large amount of libraries. The only thing what is missing in the node.js ecosystem is a long history and reference handbook which are introducing the subject to a larger audience. What we see today are some quickly created examples of Javascript code distributed over the internet. The result is, that the average user thinks, that Javascript isn't a real programming language but something which can be ignored.

From a birds eye perspective, node.js is the successor to Python 3. The virtual machine was programmed more efficient and it runs on different operating systems. The main feature is, that Javascript is used for creating productive code. That means, it's a prototyping language and a practical language at the same time. There is no need to rewrite existing Python code in C++, but the same Javascript code is used at the production server. This simplifies the programming workflow.

From the technical perspective it's pretty easy to write a hello world program in node.js. All what the user has to do is to type in the sourcecode into the normal programing IDE and configure the execute button with the nodejs interpreter. A click on run will work similar to execute a python program. That means, no webbrowser is needed, and if an error is there is will be shown in the console log. The difference between Python sourcecode and Javascript is minimal. The user has the choice if he likes to introduce functions or complete classes into his project. He can create a GUI application in html javascript or he can decide to write a GTK+ application for the normal desktop environment. That means, nodejs can be used outside the context of web-programming very well for normal desktop applications. If the user likes he can create additionally complex LAMP applications which are utilizing an SQL server and multithreading. But newbies can start with a normal logo graphics project as well.

The good news is, that in the past it was tested by different user how nodejs performs in comparison to Python 3. The answer is, that nodejs is 20x faster than a Python 3 program, https://stackoverflow.com/questions/49925322/significant-node-js-vs-python-3-execution-time-difference-for-the-same-code That means, nodejs is at the same speed like C or even a bit faster. And the examples measures only the cpu performance not the performance of a webserver which is working with parallel threads. The advantage of nodejs is here much more visible.

December 05, 2019

Is Python the best programming language?

For creating a prototype, Python is for sure the best programming language. It supports powerful object-oriented features, produces only a small amount of syntax errors and can be typed into a IDE very fast.

If the problem is not to create only a prototype but program the final production ready code, Python is poor choice. For web development, Javascript and PHP are more often used. The simple reason is, that a normal webbrowser can run embedded Javascript programs but no Python. For creating desktop applications, the C++ and C# languages are frequently used, because they can be executed very efficient on current hardware, and for low level operating system programming the C language is a here to stay.

That means, Python didn't replaced the other programming languages, but it provides an additional layer for fast creation of a prototype. No matter if a new game, a new desktop application or a new server application should be created, the first step has to do with preparing the prototype in Python. Only in the second step, the prototype gets converted into a more efficient language. What is interesting to know, that the transformation of existing Python code in one of the other languages is an easy to solve task. Efficient programming projects are working with a combination of a prototypes and production ready code. If no production ready code is needed because the prototype is thrown away after some failed tests, the Python language makes it easy to write such code snippets.

Python as a higher layer

The most interesting feature of Python is, that it can be used for testing out algorithm which can be later implemented in more efficient programming languages like C. The advantage of C is, that the language compiles into the fastest possible binary code. And exactly this speed is needed for modern desktop applications and operating systems. The disadvantage of C is, that the language is difficult to program. It was designed for a machine but not for humans. Python is the opposite of C. Programming in Python is easier than in most other language. Python is even easier to master than Visual basic and the Logo language which were both designed as beginner friendly education languages.

The interesting question is how to convert an algorithm which was realized in Python into a more professional language like C? The programmer needs to understand both languages, he has to be familiar in Python and in C. This allows to reprogram an existing algorithm. This reprogramming of code isn't a waste of time, but it's the fastest possible way in creating software. It combines the strength of Python with the power of C.

A second fact is, that most programming project doesn't need to convert into C or into C++ because the initial prototype isn't working well enough. The programmer has written some lines of code in Python, has recognized that the project has failed and decides to cancel the project. With Python as a programming language, it's very easy to step a project, because the invested amount of time was low. After a while a team or a single programmer has created lots of failed projects which are stored on the harddrive and do nothing but prove that the idea was wrong. It's important to iterate such a workflow over and over again. If somebody has created 10 failed Python project, he needs to double his efforts. This is the only way in become familiar with programming in general.

November 23, 2019

Why Python is the ideal programming language

The reason why alternatives to Python are widespread used by today's programmers has to do with a certain role a programmer plays. The assumption is, that a programmer is an expert programmer who has a deep knowledge of compiler technology and is able to write fast and efficient sourcecode. It surprising to see, that the Python language doesn't provide help for this task. It's simply not possible to write efficient sourcecode in Python.

The reason why Python is accepted by a newer generation of programmers as there preferred choice has to do with separating the programming workflow into two subparts: creating a GUI prototype and programming a piece of software. This two step pipeline is the result of modern software engineering which is trying to realize software design as a dedicated step. The basic fact why Python has become so popular in a short amount of time is, that it's the best Prototyping language available. In contrast to Matlab, Visual Basic macros and a pure graphical GUI prototyping tool, Python is more professional and available in non MS-Windows operating systems.

The funny thing is, that a written Python sourcecode fulfills certain needs great while other not. From the perspective of classical programming, Python sourcecode is something which can be ignored. Because it's slower than C++ code and less efficient than the Assembly language. The main advantage of a python program is, that it can be translated easily in any other programming language. Not because there are so many software tools available which can convert a “.py” programtext into a “.cpp” programtext, but because the manual task of doing so is an easy one.

Suppose at Stackoverflow it's allowed to post the following question. Hi guys, i have written a game in Python which is 10000 lines of code long. Can anybody help to convert the code into a Java program?” The interesting fact is, that a large amount of Stackoverflow users able to do so. Writing a Java program if the code was already tested and bugfixed in a Python prototype is an easy to realize software project. It will take longer than a single day, but it will take much shorter than creating the java code from scratch.

The most important part of programming is the prototyping step. If the Python code was developed, 80% of the overall project is done. Using Python as a prototyping language make sense, because it's much easier to write and bugfix code in Python. The compiler is very friendly to newbie programmers. And it's even possible to use multithreading. It's less efficient than in C++ but it works in a prototype.

The only technique which is more efficient than writing a prototype in Python is to search for code which was already written in github. Installing a program if the programmer has provided the repository in an archive is the fastest way of getting access to software. For example, if somebody likes to play a game of pong, he will need around a week until he has programmed the software in Python, but he can install and run the game with an existing repository within minutes.

Sometimes, Python is described as throw away prototyping language. The idea is, that the programmer develops a game in Python and if's ready he deletes the project folder, because the game doesn't make much sense. In reality, most of the written code is not new, and doesn't solve important problems. Many game development projects are started as learning / teaching experience. That means, somebody likes to learn programming and creates a bad programmed sidescrolling game, which isn't desired by anybody apart from the programmer itself.

Writing sourcecode and for throwing it away is not a mistake but the best practice method for testing out new ideas. The trick is to reduce the costs for doing so. Writing in the Assembly language throw away code is possible, but it will take very long. It's important for a programmer to anticipate, that even after investing lots of week into writing the code, the result won't fit to the needs.

October 01, 2019

Pyglet hello world program



#!/usr/bin/env python3
import pyglet
from pyglet.window import key

class GameWindow(pyglet.window.Window):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.pos=(200,200)
    self.angle=0
    self.movement=20
    imagetrain = pyglet.resource.image('locomotive.png')
    self.spritetrain = pyglet.sprite.Sprite(imagetrain)
    self.label = pyglet.text.Label('Hello, world',x=100,y=100,color=(100,100,255,255))
  def on_mouse_press(self, x, y, button, modifiers):
    pass
  def on_mouse_release(self, x, y, button, modifiers):
    pass
  def on_mouse_motion(self, x, y, dx, dy):
    pass
    #print("move mouse")
  def on_key_press(self, symbol, modifiers):
    #print("key was pressed",symbol)
    if symbol == key.A: self.angle-=10
    elif symbol == key.B: self.angle+=10
    elif symbol == key.ENTER: pass
    elif symbol == key.LEFT: 
      self.pos=(self.pos[0]-self.movement,self.pos[1])
    elif symbol == key.RIGHT: 
      self.pos=(self.pos[0]+self.movement,self.pos[1])
    elif symbol == key.UP: 
      self.pos=(self.pos[0],self.pos[1]+self.movement)
    elif symbol == key.DOWN: 
      self.pos=(self.pos[0],self.pos[1]-self.movement)
    self.spritetrain.update(x=self.pos[0],y=self.pos[1],rotation=self.angle)
  def update(self, dt):
    pass
    
  def on_draw(self):
    self.clear()  
    pyglet.gl.glClearColor(1,1,1,1)
    pyglet.graphics.draw(2,pyglet.gl.GL_LINES,
      ('v2i', (10, 15, 130, 135)),
      ('c3B', (100,100,255)*2), # one color per vertex
    )
    self.spritetrain.draw()
    self.label.draw() 

if __name__ == "__main__":
  window = GameWindow(600, 400, "pyglet",resizable=False)
  pyglet.clock.schedule_interval(window.update, 1/30.0)
  pyglet.app.run() 

Update

In a second version of the program, a dedicated class for the physics state was created. This simplified the programming a bit. The remaining commands for drawing the lines and the sprites will become easier, because once the code is written, it will draw all the elements to the screen.

Secondly, it was measured the exact cpu consumption. For 100 frames per second, the GUI app needs 15% of the totai CPU.

ps -p 31339 -o %cpu,%mem,cmd
%CPU %MEM CMD
15.1  1.3 python3 1.py

If the framerate is increased to 200 fps, the cpu consumption is 18%. It's important to know, that the only objects on the screen, are one sprite, one line and a small “hello world” text. It seems, that Python programs in general are running slow? No, that is not the case. Because a program written in high speed C++ with the SFML library has the same performance problems. It seems, that the requirements of updating the screen 200 times per second is too much for computers in general. No matter in which programming language the code was written.

Are Python dictionaries an important technique?

Python dictionaries are less known technique in creating software. It is basically a luxury version of a linked list. The user doesn't has to handle pointers and hash values, but can store and retrieve data directly into the dictionary. Additionally it's possible to create subdictionary so that large amount of information can be stored in the main memory.

The disadvantages of the idea should be mentioned. A python dictionary is similar to a data class in object oriented programming. The idea is, to create a centralized data storage which holds all the data from the game, and all the classes have access to the storage. The classes are not forced to communicate to each other but they have access to the data as default.

Usually, a centralized data storage is an antipattern in object oriented programming because it avoids OOP at all. The problem is, that the resulting structure will look the following: there is a centralized dictionary with 50 entries. And around the dictionary there are 20 subfunctions with together of 500 lines of code. Technically it will run fine, but nobody likes to bugfix such a sourcecode. Because there is no structure available. It's unclear which function is doing what.

In general, it's a good idea to avoid dictionaries and use python classes as an alternative. The class stores only a subpart of the information and holds also the function for manipulating the data. This is equal to an easy to debug sourcecode.