Strings

If you come from different programming languages the data type character might be common for you, but in Python this one doesn’t exist. A character in Python is a string with a length of 1.

To be honest I don’t think we have to go trough things like assigning a string to a variable, slicing or how to create multiline strings as these things are self-explaining. If not check out the link at the bottom of this post.

I want to jump directly into some built-in string methods, which I find really helpful.

For example you can use the format()-method to insert numbers into strings like this:

Or imagine a kid is writing on your laptop who her favorite player is. But she strangely mixes upper and lower letters. Use the lower() function:

For upper letters use upper()

Or imagine you receive a text and you want to check if a phrase is present in it (and strg+f-function doesn’t work :-P)

It will return true if it is present and false if not.

To concatenate, or combine, two strings you can use the + operator. This is a pretty cool method, because you can build your sentences like a puzzle and uncomment the words you don’t need:

The ” ” puts a space between the words.

This list would never and. I just wanted to show you here a taste of the variety of options, which exist to work with strings. Check out this further methods:

For further information about the topic watch this:

https://pythonspot.com/strings/

https://www.w3schools.com/python/python_strings.asp

#Mastery18

Lists and Tuples

Both of them actually are lists, but the difference is that a tuple can’t be modified after creation wheras a list can (e.g. add, remove, change values, sorting). They look like the following:

So what is the point in creating a tuple when a list seems to be more flexibe anyway?

One reason is that tuples are generated faster and can be iterated faster than a normal Python list. So if you want to make sure that the list will not be change or you know it doesn’t have to be changed anyway you would use a tuple to increase the performance of your code. An example to use them would be this, but make sure the positions of the numbers won’t change:

As normally lists are used more frequently I want to show you the basic operations as how to add and remove elements from it.

Output:

Soccer supports more the concept of a list, because every player, every coach and every manager is replaceable and will be replaced if the success isn’t enough. An example for the usage of a tuple might be the years of titles won, because they won’t be modified anymore.

To get a broader overview of the topic I can recommend this video:

#Mastery17

Recursion

Recursion can be described as a function that calls itself again. So you are calling a function from itsself. What happens is, that you end up in an infinite number of calling, but by default there is a limitation at 1000 times.

If we go on with our example of fans shouting a name with this function they would should “Kroos!” a thousand times until an error occurs.

Or another methapor. Let’s imagine that a function in Python can be compared to a rehearsed move in football. Then the last step in this game move would be to repeat it from the beginning. The team could do this 1000 times until it gets too tired.

Maybe you are asking yourself now, when would I need this if I can use loops instead. Fair question, but in the next example you will see why it can make sense.

You need a function to calculate the faculty of the number n. It is the product of all natural numbers less than or equal to this number n.

As we can see, we recall the function as often until n equals zero to come to the wished result.

#Mastery15

A post for For Loops

A For loop in python is used to loop over elements in a list,tuple,dictionary. So other then the before introduced “while loop” here you don’t perform a certain task so long as a defined condition remains true, but until you cover the elements defined in a list, tuple, dictionary etc.

Let’s start with a simple example. The fans want to shout every letter of their favorite player in this example its Kroos:

Like this every single letter will be printed.

We can print lists as well and notice here that they can include different datatypes:

An important factor while using For loops is the range()-function. Here you can e.g. define a range of numbers which you would like to have printed. Be aware that Python starts counting at zero and counts up. If you want to count down you have to explicitly state this with a “-1” at the end:

Or imagine you want to print the number from 1 to 20 and leave out numbers which can be divided by 5 you can combine the loop with an IF-clause:

I hope you understood the functionality of the For Loop in Python. I can recommend this video to get more information about them:

#Mastery14

While Loops

while loop in Python programming repeatedly executes a target statement as long as a given condition is true. If found this chart and want to show it to you as it describes the way of using while-loops pretty good:

Chart found on: https://www.tutorialspoint.com/python/python_while_loop.htm

So what we can see is that you define a condition and if it turns true the assigned conditional code will be executed otherwise the loop ends.

In most soccer stadiums in Germany the stadium announcer calls the name of every player at least 3 times and the fans have to repeat them everytime. For the best players the fans shout “Fußballgott” (god of soccer) three times. How can we implement this in Python:

The “+=” adds one to the varible i with every iteration until the condition turns to false

The next thing I want you to understand is how loops into loops function. Imagine the stadium announcer says the name of the player one time than the fans scream “Fußballgott” three times and then the stadium speaker says the name one more time:

Methaporically spoken, when the fans beginn to sign it is first their turn to finish their part until its the announcers turn again. So first the inner loop will be completed until it jumps back to the outer part.

I hope you understood the basic functionality of the while loop. If you want to get further information e.g. what to do with the “break” or the “continue” into a loop have a look at this resource:

https://realpython.com/python-while-loop/

#Mastery13

Conditionals and Nesting

Through the usage of conditionals Python performs different computations or actions depending on whether a specific constraint evaluates to true or false. The syntax looks as following:

So lets say you want to test who scored more goals in the Champions League (CL), Ronaldo or Messi you can do it as follows:

The next step is to use the “else”-Statement. So depending on if our logical expression is right or wrong the “else”-Statement will be executed or not. To make this more practical let’s have a look at an example. Imagine a family dad wants to go to a soocer match, but isn’t sure if his children are old enough to get in and what he has to pay for them. We will solve this through this little program:

Notice the following: We can see a nested if-else here (the yellow part). If the age was 10 the compiler would directly jump to the else at the bottom. If the age is higher or equal to 11 it shows the prices. You can see that nesting is nothing more than placing one or more if statements within another if statement. Furthermore, we see the “or” operator, which is pretty self-explaining.

After we got to know the “if else” structure, now we introduce the “elif”, which is short for else if. It allows us to check for multiple expressions. If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks.

Lets build an example on this. Assume you know the number of seats, which will be free in the stadium during the soccer game. Now you want to know how the atmosphere in the stadium will be based on this information:

For further information I on conditionals I can recommend this webpage:

https://www.programiz.com/python-programming/if-elif-else

#Mastery11 #Mastery12

Creating modules

Based on what we learned in my blog posts before creating a module can be done by writing a python file and import it to your main program (remember that both files have to be in the same directory!).

Imagine you want to use a function that prints a list of your favorite soccer players. And create it like this:

But now you are changing your mind and you think that it is more valuable to print a list of the best all times players. But you are in a hurry, because your soccer game starts in two hours so you don’t want to write the function again anymore. Solution –> import the module to your main program:

Notice the following: The compiler will run through the whole module before it imports the function to the main module. So if you would uncomment the “#my_favoriteplayers(bestones)” in the first module, it would print the first list as well and then print the list from the main module under it.

So in general, I would recommend to not return the function in the module you wan’t to import as it’s probably not the one you want to see in the main module.

Probably the two best players of two centuries.

#Mastery10

Using Modules

In programming, a module is a piece of software that has a specific functionality. For example, when building a sudoku game, one module would be responsible for the game logic, and another module would be responsible for drawing the game on the screen. Each module is a different file, which can be edited separately.

Importing modules is similar to importing functions and is done by writing import <name of the module> . Every Python file can be referenced as a module. The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

So the steps you do are:

  1. Save your code in a file e.g. like “myfirstmodule.py” (Notice: it is has to be in the same directory as your main file)
  2. Import your module: watch my blog post Mastery 07 for the different options on how to import libraries and functions, it is the same here.
  3. Use the module for your purposes in your current code.

Example:

With this knowlegde you can directly start. If you want to go more into detail I can recommend this page: https://www.w3schools.com/python/python_modules.asp

#Mastery09

Creating functions in Python

In the last post you saw how to call functions. But how to create them?

It’s pretty straightforward you simply have to tell the compiler the name of the function and the parameters. It looks like this for a simple multiplication function:

The name is “mult_function” and the parameters are “a,b”. We tell the compiler to multiply them.

Keep one thing in mind: You can’t have two functions with the same name. Think of it like a rehearsed play which is given a name which the coach screams when it is time to play it. Wouldn’t it be super confusing to take the same names for different plays? Nobody knew what to do then. Neither would Python do (= no function overloading), but it solves this dilemma by only using the latest defined function.

You can do a lot with functions. For example you can calculate Fahrenheit to Celcius as I did it here:

#Mastery08

Calling Functions in Python is like performing a rehearsed play in soccer

First of all three important things about functions:

  1. A function is a block of code which only runs when it is called.
  2. You can pass data, known as parameters, into a function.
  3. A function can return data as a result.

In other words: A function helps you to approach a challenge you want to solve in a more efficient way with less error potential. Defining the content of a function once, you can easily apply it to different use cases as well and don’t have to write the code over and over again.

In the sense of soccer a function is like a rehearsed play, which can be repeated over and over again in different situations to solve a challenge.

The cool thing is, that there are already existing functions in Python. But before you can use them it is often the case, that you have to import them.

To import the whole library (in our example “math”) you can do this by libraryName.functionName():

You can import only one function from a library, then you can call it by just using its name:

And if you don’t like the default names of the funtions you can just assign your own names to them e.g. the one of your favorite soccer player:

All the examples shown above will return the value of pi. One more thing:

It is important to understand what the “return”-Statement does within the functions and how it can be seperated from the “print”-Statement. The best resource I could find on the internet on this was this video:

#Mastery07