Module 2 (Python)

Aug 26, 2022·
Gitgotchi
Gitgotchi
· 12 min read
Photo by David Clode on Unsplash
Date
Aug 26, 2022 12:00 AM

Python

In this module the main focus was on the programming language called Python. It is an open-source project and a quiet useful language with multiple different and complex extensions. Within the module I will mainly learn the basic commands and structures which will give me the knowledge to create little programs with the possibility for bigger ones in which I then just need to learn some new theory.

As IDE I used Spyder which is specificly made for Pyhton code and is provided by Anaconda. It has mutliple features for a good workflow and you have control over everything you need. Here’s a quick overview how it looks:

Spyder IDE developement environment

Spyder IDE developement environment

  • Blue -> Folder/File structure and overview
  • Pink -> Editing space in which you write your code
  • Orange -> Overview of all variables you used in your code
  • Yellow -> Execution field where all occured errors and program results are shown

Primitive Types

In Python there are different types of data. The basic ones are primitive types.

  • Integers -> Only whole numbers
  • Floats -> Decimal numbers
  • Strings -> Signs/Words (whole alphabet inc. numbers and special signs)
  • Boolean -> Checks if a value is true or false
Initialization of primitive types

Initialization of primitive types

String-Operators

String operators are made to to edit strings in specific ways. You can change individual characters, capitalize them or even cut them out of the word completely.

String operators used on the word ligma

String operators used on the word ligma

Output of the string operators

Output of the string operators

Non-Primitive Types

Non-primitive types are more complex data used in Python mostly to save variables or other data in a structure to get access to this data in different ways.

Lists

  • Lists are used to save data in it.
  • They are ordered so you can access it with an index.
  • They are mutable which means you can still add or remove items after the creation.
  • Duplicated items are possible. The items dont have to be unique.
  • You can combine different data types in one list.
List creations and access with indexes

List creations and access with indexes

Outputs of the lists

Outputs of the lists

Arrays

  • Arrays also store items and are similiar to lists.
  • They are ordered and mutable as well.
  • They can’t contain different data types.
  • Can be added, divided etc. together without problem because they can only contain one type of value (mostly numbers).
  • Used for large data types and mathematical use cases.
  • In Python they are only accessible through an array module or a NumPy package.
Creation of a mathematical random number estimation generator with NumPy

Creation of a mathematical random number estimation generator with NumPy

Output

Output

Tuples

  • Tuples have the same properties as lists.
  • One exeption is they can’t be changed (add or remove an item) so they are immutable.
  • You can let other items of another tuple join the original tuple to creat one big tuple.

Sets

  • Similar to lists as well.
  • They aren’t ordered.
  • They can’t contain an item twice -> you can add it to a set but it won’t be printed.
  • Through the unique items they are really efficient in data processing.
  • Items can have a hash value because every item is unique.

Dictionaries

  • Also contain values but with a special structure -> they have a key:value structure.
  • Every item (“key”) needs a related value.
  • Keys can’t be doubled but the value can be overwritten.
Creation of a dictionary with keys and related values

Creation of a dictionary with keys and related values

Output of the accessed dictionary

Output of the accessed dictionary

Files

Access to non-primitive types

Program codes:
Click to view the code
List creation and access of the list

List creation and access of the list

Output

Output

Array creation and access of the array

Array creation and access of the array

Output

Output

Tuple creation and access of the tuple

Tuple creation and access of the tuple

Output

Output

Set creation and access of the set

Set creation and access of the set

Output

Output

Dictionary creation and access of the dictionary

Dictionary creation and access of the dictionary

Output

Output

String list creation and access of the string list

String list creation and access of the string list

Output

Output

Operators

Operators are mainly used to change the value of a variable/storage. Below I have listed the ones you use in Python and how they work.

Arithmetical Operators

Arithmetical operators are mathematical operators which include addition, subtraction, multiplication, divison, exponentiation, modulus and floor division. In the following pictures I used all types of data and tried out with which of them the calculations work.

Program codes:
Click to view the code
Initializing of variables, addition and subtraction of all data types

Initializing of variables, addition and subtraction of all data types

Outputs of the calculations

Outputs of the calculations

Divison, multiplication and exponentiation of all data types

Divison, multiplication and exponentiation of all data types

Outputs of the calculations

Outputs of the calculations

Floor division and modulus of all data types

Floor division and modulus of all data types

Outputs of the calculations

Outputs of the calculations

Relational Operators

Like the name indicates the relational operators relate a value to another value and the tells you if this reltaion is true or false. So it gives you only boolean values as an output.

Program codes:
Click to view the code
Initializing of the variables and different relations of all data types 1.0

Initializing of the variables and different relations of all data types 1.0

Outputs of the calculations

Outputs of the calculations

Different relations of all data types 2.0

Different relations of all data types 2.0

Outputs of the calculations

Outputs of the calculations

Assignment Operators

With assignment operators you can assign values together with an operation to the existing variable (just a combination out of an arithmetic operation with the variable itselfe in it). Here a quick overview:

Overview of all assignment operators / Source: W3schools.com

Overview of all assignment operators / Source: W3schools.com

Logical Operators

The logical operators also can only have boolean outputs because they are used for conditions to tell if something is fulfilled. The normal use is to combine conditional statements and they contain the operators ‘and’, ‘or’ and ’not’.

State machines

State machines are a graphical constructions of different states in an algorithm. An algorithm is simply a procedure of operations/commands. There are two categories of state machines:

  • Infinite state machines
  • Finite state machines
    • deterministic (State a always ends in state b)
    • non-deterministic (State a can end in multiple states)
State machine model task:
Click to view the models
Deterministic state machine of a vending machine process

Deterministic state machine of a vending machine process

Non-deterministic state machine of the word creation process (anna & ananas)

Non-deterministic state machine of the word creation process (anna & ananas)

Loops

If-Loops

If-loops normally work with so-called if statements:

  • First you give the computer a specific condition which should be achieved to exectue a piece of code -> “if”
  • Then if this goal can’t be answered with true he goes to the next condition where you do the same (you can do this as much as you want) -> “elif”
  • After every line could be answered with false he goes to the last piece of code which gets only executed if no statement in the code can be answered with true -> “else”
Short example of an if-loop

Short example of an if-loop

While-Loops

While-loops on the other hand have to be negated otherwise the loop just does it infinite times because the program assumes the condition is always true so he always does the followed piece of code. To negate the loop you have to implement some sort of a break or change of the boolean value.

Short example of a while-loop

Short example of a while-loop

Output of the while-loop

Output of the while-loop

For-Loops

The last of the three loop types are for-loops. They normally don’t work with boolean values with regard to their execution process. They just loop through the code a specific amount of types. You can give them to different variables to define this amount and where he should do this or with what. The first variable can just be an element in a list or something. The second variable tells the loop either where (e.g. in which list) or how many times (e.g a range).

Two short examples of a for-loop

Two short examples of a for-loop

Output of the for-loops

Output of the for-loops

Loop Task:
Click to view the code
For- & while-loop solution for counting to 100 in steps of 2

For- & while-loop solution for counting to 100 in steps of 2

Output for both loops

Output for both loops

Functions

Functions are a simple way to don’t write a specific code multiple times if you need it more then once in your program and still be able to flexible change the parameters of the code. You can give a function arguments/values it should use every time you call it or if it’s a constante you just define a local variable in the function itselfe. Here are some typical basic examples how you can use a function in a program:

Examples on how you can use functions

Examples on how you can use functions

Output of the example functions

Output of the example functions

Return command

The ‘return’ command is normally used in functions to return a result or value. After this command was exectued the rest of the lines in the function getting ignored and the you exit the function. If you call the function somewhere in the program it only one single run time with the return statement at the end.

Examples from a return function

Examples from a return function

Output of the return function

Output of the return function

Yield command

A yield functino on the other hand can give back multiple values, dosen’t exits the function after the command ‘yield’ and you can pass down an iteration of values as a generator. This type is mainly used for big data and has the advantage of not destroying the local variables.

Examples from a yield function

Examples from a yield function

Output of the yield function

Output of the yield function

Function Tasks:
Click to view the code

Task 1:

Creating a BMI-Calculator

Creating a BMI-Calculator

Output of the program

Output of the program

Task 2:

Create a program that outputs a Fibonacci-List with a ‘return’ command

Create a program that outputs a Fibonacci-List with a ‘return’ command

Output of the Fibonacci-List up to the wanted ending number

Output of the Fibonacci-List up to the wanted ending number

Task 3:

Create a program that outputs a Fibonacci-List with a ‘yield’ command

Create a program that outputs a Fibonacci-List with a ‘yield’ command

Output of the Fibonacci-List up to the wanted ending number

Output of the Fibonacci-List up to the wanted ending number

Task 4:

Create a a function that iterates thorugh a range of numbers

Create a a function that iterates thorugh a range of numbers

Output of the number generator with choosen values

Output of the number generator with choosen values

Classes

Also classes exist in Python even this language isn’t initially made for OOP (Object Oriented Programming). Classes just work as a structure tool for the coder. With this tool he can use a program multiple times with different argument and doesn’t have to copy paste the program snippets. Here some examples:

Two examples for classes made in Python

Two examples for classes made in Python

Output from the call commands

Output from the call commands

Everything from the class to functions and objects as well as the inputs can be changed using this structure. This can be done anywhere in the program and makes the whole execution of one specific “code base structure” multiple times quiet easy to handle.

For a proper use of classes you normally have to keep an eye on 4 different things. To understand this in a use case look at the example below :

Example class called Person to show the structure in a use case

Example class called Person to show the structure in a use case

  • The class itselfe (Neon green)
  • The initiation; in generall called ‘__init__function’ (Orange)
  • Define Objects which using the classes (Light blue)
  • Methods or also called functions (Purple) which execute some different code with the objects in the class (Yellow)
    • You can also call functions that include other functions in the same class (Pink)
    • Like I already mentioned you can also change the arguements/variables whenever you like (White)
Output of the class calls

Output of the class calls

Lambda Functions

Lambda functions or also called anonymous functions don’t have a name. They take a specific amount of arguments but only one expression (lambda arguments : expression). You normally use them in other functions or for quick calculations as well as if you want to use variables that you don’t want to define somewhere in the program.

Examples of the use of lambda functions

Examples of the use of lambda functions

Output of the two print statements

Output of the two print statements

Like in the first example you can just create the variable ‘a’ without initiate it somewhere as well as just make another function in the newly created function ‘myfunc’. The second example just shows that you can use lambda functions also as standalone functions and instantly execute them with the arguments given directly after the function.

UML

Unified Modeling Language (UML) is a way to create a graphical illustration of a software, the structure of the software and how it should be set up. They normally include use-cases, processes, communication, distributions etc. In the following section I shortly go a little bit into how can show algorithms, use-cases and classes (in relation to program code).

  • A typical diagram type for algorithms is the Nassi-Shneidermann diagram
    • I made one for a customer order in an online shop
    • Built with a typical if/else statements (TRUE / FALSE)
UML that represents an algorithm for a customer order

UML that represents an algorithm for a customer order

  • For use-case diagrams have to include a few more specifications
    • Descriptions of the use-cases
    • Pre-condition
    • Post-condition
    • Paths (main and if available alternative one)
Use-case diagram that describes an shopping system / Source: visual-paradigm.com

Use-case diagram that describes an shopping system / Source: visual-paradigm.com

  • Last but not least we have the class diagrams which should show a software intern process
  • You hve different classes
  • Classes can have associations
  • A parent class always has at least on child class as a component (parent example: Account class)
  • A child class can’t exist without a parent class (child example: Customer class, Bank class etc.)
Class diagram of a user account / Source: visual-paradigm.com

Class diagram of a user account / Source: visual-paradigm.com

Additional Section (Plotly)

Further I explored the application Plotly for myselfe a little bit (wasn’t included in the Python module). I thought it’s a really cool tool to make customized, interactive and goodlooking graphs with relatively “simple” code pieces. Everything is made for a user to get access to predefined graph samples which he can just customize with different commands from the libraries of that specific graph type.

Neverless I also encountered some deeper problems with different sceneries and combinations (which costed me hours 😞 but I still learned a lot), which then requires a big amount of knowledge pretty fast and goes into enormous depth as well as taking up a lot of time. Thus both sides the complexe ones as well as the simple ones existing for this tool.

Here some graphs I made with Plotly (if you want to experience the diagrams interactively click on the following link to download the ZIPs -> ZIP-Files):

Graph 1

Graph 1

Graph 2 (with 2 subplots)

Graph 2 (with 2 subplots)

Graph 3

Graph 3

Pygame

To be able to create some graphical implementations into a python codes I learned some theory about Pygame which is mainly used for GUIs in gamelike applications but quit comfortable to represent gameified applications.

In order to learn commands better and understand what is happening I programmed a little jump game (simple) like you know it from the Explorer browser if the internet doesn’t work.

Below I show how it looks like and also what code I created to run it on my PC (I’m still working on a web-based solution so you can also try the game by yourselfe):

Jumpgame created in Pygame:
Click to view the game
Home Screen

Home Screen

In-Game

In-Game

Jump over obstacle

Jump over obstacle

End of the game with your score

End of the game with your score

Click to view the code
Code section 1

Code section 1

Code section 2

Code section 2

Code section 3

Code section 3

Code section 4

Code section 4