Python Dictionaries and While Loops for Beginners

Introduction

Welcome to the post about Python dictionaries in this series Learn Python by Programming Fundamentals First, where we practice programming fundamentals using the Python programming language.

In this post we will continue to work on the training app and build more functionality by utilizing Python dictionaries.

As you might have guessed, dictionaries are a fundamental part of most programming languages, therefore it’s important to learn how to use them efficiently. As you move on and learn new languages, e.g. Java or C++, the same concepts will apply.

Dictionaries belong to the category fundamental data structures, and are used whenever you want to manage pair-wise information, or a key-value format in programming terms. One example where this is used is in your phone. When you search for a contact, that name is linked to a phone number. We could say that the name has a direct relationship to the number. Whenever these relationships are necessary to represent in a program, a dictionary is usually a good starting point.

Finally, we will build on the concept of loops and look at while loops together with functions as well. Functions are part of a deeper topic that we’ll cover in upcoming posts. The exercises at the end should be a priority to do in order to practice what you’ve learned.

You can read more about dictionaries in the official Python docs at: https://docs.python.org/3/tutorial/datastructures.html

Purpose

The purpose of this article is to help you understand Python dictionaries, functions and while loops and how to use them in your own programs.

Goal

By the end of this post you will be able to

  • Understand what a dictionary is
  • Create and modify dictionaries
  • Use the built-in dictionary methods, such as .get(), .items()
  • Know when you should use a while loop

Prerequisites

You must have Python installed and be able to start IDLE or your IDE to follow along. You should be familiar with how to create modules/script and run a Python script, either from the terminal or the GUI window.

A good starting point is this link: How To Install Python On Your Computer

Additionally you should have finished Python and the Building Blocks of Programming and Python if-statements and loops – how to be lazy

If you found anything difficult in previous posts, don’t hesitate to let us know! Contact Us

Try It Yourself: Python Dictionary Example

Look at the following code, copy and paste it into your IDE of choice, e.g. IDLE or PyCharm. If you run the program, what do you expect to see? Think about it and compare it with the output.

# A simple dictionary with some fruits and their colors
fruit_colors = {
    "apple": "red",
    "banana": "yellow",
    "grape": "purple"
}

# Accessing a value
print("The color of an apple is:", fruit_colors["apple"])

# Adding a new key-value pair
fruit_colors["orange"] = "orange"

# Updating a value
fruit_colors["banana"] = "green"

# Deleting a key-value pair
del fruit_colors["grape"]

# Looping through the dictionary
for fruit, color in fruit_colors.items():
    print(f"{fruit.title()} is {color}.")

Dictionary Concept Breakdown / Code Analysis

Let’s start by inspecting the new syntax. The dictionary definition for fruit_colors starts with curly braces ( {} ), and it’s stored in the variable fruit_colors. Notice the format for defining a dictionary is "key":"value".

The result is a dictionary that contains three keys: apple, banana, grape and three values red, yellow, purple. These are the three pairs in the dictionary: apple+red, banana+yellow and grape+purple.

You can use square brackets [] in order to access a key in the dictionary, which is used in the print-statement. Python also has a built-in method .get() that can be used to retrieve a key’s value.

Finally, in the for-loop we use the dictionary method .items() to access the key and value at the same time. In each iteration, the variables fruit and color are assigned from the dictionary fruit_colors.

Project – Workout App Exercise Details

Now using this new concept, let’s get back to our project again and see if there’s any good use case for a dictionary.

week = 1
schedule = 'Workout A'
exercises = ('Bench press', 'Deadlift', 'Squat', 'Biceps curl')

# New code for dictionaries here soon
# ...
# ...

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

selected_exercise = None
if response == 'Yes':
    print('Here are all the exercises:')
elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

    selected_exercise = input('Which exercise would you like to know more about? ')

if selected_exercise in exercises:
    print(f'You chose {selected_exercise}. This is a fundamental exercise for building strength.')
else:
    print('That exercise is not in the schedule.')


Next we will implement the idea to include a description for each exercise. It’s easy to extend the program and provide more information about an exercise if necessary. For example, to add a video link on how to perform an exercise, you could store that info in a dictionary as well.

In order to put this idea into code, let’s create a new variable called exercise_details that will (you guessed right) hold the description associated with an exercise. Here’s a suggestion, you may change the description text yourself.

exercise_details = {
    "Bench press": "Compound exercise for upper body",
    "Deadlift": "Compound exercise for lower body and core",
    "Squat": "King of exercises, compound and overall legs",
    "Biceps curl": "Isolation exercise for the upper arms"
}

Now we can use two Python built-in methods to query the dictionary. You’ve already seen items() above, Python also provides .keys() and .values() for returning view objects of keys and values respectively.

print(exercises)
print(exercise_details.keys())
print(exercise_details.values())

Output

('Bench press', 'Deadlift', 'Squat', 'Biceps curl')
dict_keys(['Bench press', 'Deadlift', 'Squat', 'Biceps curl'])
dict_values(['Compound exercise for upper body', 'Compound exercise for lower body and core',
               'King of exercises, compound and overall legs', 'Isolation exercise for the upper arms'])

You might have noticed the output of exercises and calling .keys() on the dictionary are rather similar. Remember that exercises is a declared variable that holds a tuple. It’s related to the exercise_details keys by design from the programmer (us). However, the tuple is a different data structure from the view object returned by .keys()

The view object is a dynamic representation of the keys in a dictionary, meaning it always reflects the current state of the dictionary. A tuple however, is immutable, meaning it cannot be changed after it was created.

While Loop – The For-loop’s cousin

The purpose of a while loop is to repeat a code block until a condition is met. This is also called iteration in programming terms. Both the while and for loops are used frequently. Eventually you’ll develop an intuition on when to use them.

The program has to handle errors when users enter information into the program.

If you run the program and press Enter at the first question, the program will continue to the next question without any error control. That is not ideal.

In our program, the idea is not to proceed to the next question, until a valid choice has been made by the user. Therefore we want to repeat any question or choice prompted to the user.

A while loop can repeat a code block until a condition is met. That’s the idea we will implement next in our program.

“”” Until the user has left a valid choice, repeat the code block “””

Let’s first take a look at the anatomy of a while loop.

while boolean-expression:
    code block
    ...etc

This will run the code block repeatedly as long as the boolean expression is True. A boolean expression is an expression that evaluates to either True or False.

Notice the indentation of the code block. It is also possible to use a break statement inside the code block in order to stop the while loop, we will cover an example of this below.

Here’s another example of a while loop that repeatedly prints Hello to the console, don’t run this program (yet).

while True:
    print("Hello")

The word Hello is printed after the first iteration, then the program will start the next iteration, and determine that the condition is still True. Therefore, the program enters the code block again. The code block that prints Hello is executed again, then the next iteration starts and the program repeats this process infinitely.

Workflow of the program:

1. while True mean "yes let's enter the code block"
2. print Hello
3. Go back to step 1) and evaluate whether the expression is True (which it is)
4. print Hello

In contrast to the if statement, we need a mechanism to break out of this loop. The way to handle this is to simply add a break statement in order to exit the loop.

while True:
    print("Hello")
    break # Don't remove this

Now our program will print the word Hello once and immediately finish and exit the loop. If you were to remove that break statement as in the first version, the program would continue to print forever, and you’d have to kill the program somehow, probably by entering Ctrl-C or closing the IDE.

With this in mind, it’s important to construct a while loop such that it doesn’t result in an infinite loop as it’s called. It takes a little practice, but it’s nothing to worry about as continue to improve your understanding of programming loops.

Another common use case of a while is during counting. Here’s what that looks like

counter = 0
while counter < 10:
    print("Counter is at ", counter)
    counter = counter + 1 # Increment the counter in every loop

This doesn’t result in an infinite loop because the counter increases during every iteration. Eventually, it will reach a number that’s greater than 10, thereby evaluating the boolean expression to False. Run the program and see if you can understand how it works.

Before you move on

Experiment and see what changes when the condition is set to 15 instead of 10. If you switch the condition to greater than instead, i.e counter > 10 – what do you notice?

Let’s look at a final example before implementing this in our own program.

Here’s a similar construct to the previous example, but the idea is still to use a break statement to exit the loop.

At first sight, it might look like an infinite loop, but because an exit condition exists, it’s possible for the program to eventually exit, when the user types Quit into the program.

# Almost an infinite loop. It keeps running until the user type Quit however.
while True:
    # Ask the user for input
    answer = input("If you want to quit this loop, please type Quit ")

    if answer == "Quit":
          print("Breaking out the loop...see you next time")
          # Special keyword to exit the loop
          break
    else:
          print("Ok, so you dont want to quit...trying another turn")

In the above example, the break statement is placed after a conditional statement (if), it’s not necessary to place it at the beginning of the loop. It’s up to the programmer to decide under which conditions the loop should break.

Finally, the construct of while True is very common in menu systems and when a program waits for user input.

While Loop Concept Breakdown / Code Analysis

Let’s repeat what we’ve covered so far.

A while loop consists of a condition and a code block. The loop executes the code block as long as the boolean expression evaluates to true.

We saw that a while True: loop repeats a code block forever, the only way to break out of the loop is to execute a break statement somewhere inside the code block. Where and how this is done is up to the programmer. In the previous example this happens when the user enters Quit.

In contrast, while False: would not be useful as the program would never enter the loop, and just skip to the next statements of the program.

Run the examples until you start to understand how they work. If you get stuck, feel free to reach out at -> Contact Us

Project continued – While Loop

Back to our training app project, let’s focus on the first parts of the code. If you remember, we want to validate the answer from the user before moving on.

Therefore, we’ll wrap our first question inside a while True: loop instead of continuing when user enters something invalid. We can also improve the check with the operator in as we saw in the previous post on the in operator.

while True:
    response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

    if response in ("Yes", "yes"):
        print("Here are all the exercises:")
        for item in exercises:
            print(item)
        break # Break out of the loop, we don't want to repeat the question anymore
    elif response in ("No", "no"):
        print("Cool, no hard feelings!")
        break
    else:
        print("You must answer Yes/No, please try again")

This looks much better. However, we should also notice that after running this program, in the case the user enters No it would be incorrect and weird to continue to the second question. So we’ll have to fix next.

answered_yes = False # Add a new variable
while True:
    response = input(
        "Would you like to see all exercises in the training schedule? (Yes/No) "
    )

    if response in ("Yes", "yes"): # Check membership in the tuple
        answered_yes = True # Store the user's choice
        print("Here are all the exercises:")
        for item in exercises:
            print(item)
        break
    elif response in ("No", "no"):
        print("Cool, no hard feelings!")
        break
    else:
        print("You must answer Yes/No, please try again")

if answered_yes: 
    selected_exercise = input("Which exercise would you like to know more about? ")

    if selected_exercise in exercises:
        print(
            f"You chose {selected_exercise}. This is a fundamental exercise for building strength."
        )
    else:
        print("That exercise is not in the schedule.")


We introduce a new variable called answered_yes that is set to True in the same code block where we print all the exercises, because that’s when we know the answer from the user is Yes. This is also called a state variable, or sometimes a flag variable and it comes in handy when a program must deal with control flow during execution.

Later in the program, we use an if statement to check the value of the state variable, and only if its value is True do we print the second question.

At this stage, we have fair amount of code in our program that works well. We have a small interactive Python program using loops, conditionals, tuples, and dictionaries, not a small feat!

Here’s the complete Python program so far, go ahead and run it in your own IDE.

week = 1
schedule = "Workout A"
exercises = ("Bench press", "Deadlift", "Squat", "Biceps curl")

# Unused variable for now
exercise_details = {
    "Bench press": "Compound exercise for upper body",
    "Deadlift": "Compound exercise for lower body and core",
    "Squat": "King of exercises, compound and overall legs",
    "Biceps curl": "Isolation exercise for the upper arms",
}


answered_yes = False
while True:
    response = input(
        "Would you like to see all exercises in the training schedule? (Yes/No) "
    )

    if response in ("Yes", "yes"):
        answered_yes = True
        print("Here are all the exercises:")
        for item in exercises:
            print(item)
        break  # Break out of the loop, we don't want to repeat the question anymore
    elif response in ("No", "no"):
        print("Cool, no hard feelings!")
        break
    else:
        print("You must answer Yes/No, please try again")

if answered_yes:
    selected_exercise = input("Which exercise would you like to know more about? ")

    if selected_exercise in exercises:
        print(
            f"You chose {exercises[selected_exercise]}. This is a fundamental exercise for building strength.
            {exercise_details[selected_exercise]}.
            "
        )
    else:
        print("That exercise is not in the schedule.")

Exercises

Here are some exercises to try on your own, you can try to building upon the program however you like.

  1. Create a new dictionary with your own keys and values. The dictionary should contain key-value pairs for countries and capitals. Create a second dictionary that stores name and age pairs. Print the dictionaries.
  2. Retrieve a value from your dictionaries using a key and the [] notation. What happens if you specify a non-existent key or make a typo?
  3. Add and update a values in your dictionaries
  4. Add a new key-value pair using the bracket syntax: your_dictionary[key] = value
  5. Update an existing value using the bracket syntax. How is this different from accessing a key with a typo?
  6. Remove an item using del and .pop().
  7. Use a for loop to print all keys in your dictionaries.
  8. Ask the user for a key and check whether it exists in the dictionary.
  9. Write a code block that swaps the keys and values. Remember you can use .keys() and .values().
  10. Use the method .items() on the exercise_details variable. You can decide where in the code to place it and print the contents.
  11. Inside the if selected_exercise in exercises: use another print to print and fetch the value from exercise_details using .get().
  12. Add a third print to print the details, but this time using the [] notation.
  13. Add another alternative to also accept the word “quit”.
  14. Search the Python documentation for string methods, see if you can find a way to remove whitespace from the input string before checking it. So the program should also accept accidental spaces, like “quit “, ” Quit”. It’s enough to handle spaces around the word. https://docs.python.org/3/library/stdtypes.html#string-methods

Summary

In this section, we explored two important Pythoon programming concepts: dictionaries and while loops. These concepts are fundamental building blocks used in many real-world Python programs.

We have also covered Python dictionary methods and learned how dictionaries can be used to store and organize data inside a program.

We have also explored a simplified yet common process for how a program can be developed. We started with an introductory text and expanded it step by step by asking the user a question. We also printed the user’s response.

It’s not easy to build everything at once, we allowed the program details to grow naturally and also handled the control flow of the program better in small improvements. It’s good to think of this process as normal.

In the next section, we’ll continue working with Python control flow and how to write our own functions. Functions are used to break down a program into logical components, and helps us write program that consist of smaller building blocks. We’ll also look into how we can handle text files in Python.

Think about how you want to develop the Training App further. For example, you could let the user enter their own exercise descriptions or store workout history. The sky is the limit!

See you in the next post!

Introducing a new Krita Plugin – Buttonz Booster

Krita has been my go-to application for digital drawing and editing. It’s a powerful open-source painting program, on par with professional software like Photoshop, and loved by artists worldwide

Where does Buttonz Booster fit in?

The purpose is to save you some clicks, and it allows you to create a new document with a predefined size, simple and easy.

You can install it directly from Krita, first download the ZIP file

Buttonz Booster

Alt. download link
Alternative download link

How to Install

  1. Go to menu Tools->Scripts->Import Python Plugin from File…¨
  2. Locate the ZIP file you just downloaded. The install should prompt if everything went OK or not.
  3. Restart Krita if all went fine.
  4. Activate Settings->Docker->Buttonz Booster

I’m happy to share it with you all, and are there any quick actions you’d like to add? Let me know!

Python If Statements and Loops (Lazy Beginner Tutorial)

Welcome to the beginning parts of Learn Python In A Normal Way. In this series we’re working on our own Training App. The series focuses on how to get up and running with logical thinking and programming with Python, and it should suit the beginner since doing assignments is what makes you learn quicker.

Make sure you’ve read the previous part Python data structures part 1 – a look at variables and lists

Why It Matters (Purpose)

The purpose of this lesson is to cover Python if statements and loops. Writing a program is usually about making decisions based on different conditions. Changing path of execution in a program is done using if statements. Programs also store information and interact with users. During these interactions, you often need a menu system or a conversational flow. This is where loops come into play.

What You Will Learn (Goal)

By the end of this post you can

  • write and understand a Python if statement
  • write and understand a Python for loop in a simple scenario
  • write and understand how to Python boolean expressions

Prerequisites

You must have Python installed and be able to start IDLE to follow along. You should be familiar with how to create modules/script and run a Python script, either from the terminal or the GUI window.

A good starting point is this link: How To Install Python On Your Computer

Additionally you should have finished Python data structures part 1 – a look at variables and lists

If you found anything difficult in that part, please let us know! Contact Us

Python If Statement – make a choice in your application

A Python if statement gives you more control over a program. With an if-statement, we use the information of a variable to make a decision in your program. For example, if you want to display all exercises when the user responds “Yes,” and show a different message if the user responds “No,” you can use an if-statement.

Let’s see what they look like!

Code Block to Copy

Try the following code in a new script, which we’ll call workout_v2.py:

week = 1
schedule = 'Workout A'
exercises = ('Bench press', 'Deadlift', 'Squat', 'Biceps curl')

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

if response == 'Yes':
    print('Here are all the exercises:')
    # more code here ...
elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

Python If Statement Analysis

The if statement in previous listing highlights three branches:

  1. Condition with if: If the user types “Yes,” the code block following the if statement is executed. We call this the first conditional block. The boolean expression (response == ‘Yes’) evaluates to either True or False, depending on what the user typed.
  2. Alternative with elif: If the user types “No,” a different message is displayed.
  3. Invalid response: If the response is something other than “Yes” or “No,” the program shows a message explaining that only those answers are valid.

It’s plain English, yet so important to get it right with Python syntax and indentation. Notice the colon, and the indentation for each block. Otherwise you will get a syntax error when you try to run the program.

Run the code and try typing “Yes,” “No,” and an invalid response (like “Maybe”) to see what happens. You’ll notice that the program becomes more interactive and adapts to the user’s input now. Pretty neat, right?

A note about conditional logic

When we write an if-statement, the code block or the branch to enter is evaluated according to a boolean expression. It’s the same as asking a Yes/No question, but in the computer world we call this True/False result.

The if-statement anatomy consists of the conditional block and the boolean expression

if True:
    print("This will always be printed")

When we compared the user’s answer of “Yes” or “No”, the result of that comparison would either be True or False internally.

On the other hand, if we’d write

if False:
    print("This will never be printed")

Then we’d never enter that block. Why?

Here are more examples of boolean expressions, where we use the comparion operator greater than >. The first evaluates whether 5 is greater than 10 (False obviously). The second checks if the length of the variable some_list exceeds 100.

if  5 > 10: # Evaluate to False
    print("5 is greater than 10, is it really?")

if len(some_list) > 100: # Test if the list has more than 100 elements
    print("You have more than 100 elements in the list")

The purpose is to only execute part of the code when the boolean expression is True. In the above example it’s simply just one print statement. This is something we will see more of and learn about as we move along.

This type of logic becomes important as you want develop the program, also when when you want to put constraints in your program.

Imagine a scenario to never allow more than 5 exercises per workout day, or where you can limit the number of sessions total per week. All these things require some kind of conditional logic to exist in your program. Therefore as you gain experience and develop the program, it’s only you as the designer of the program that can decide what is valid in your program or not.

Finally, let’s look at how to combine multiple expressions, to check several conditions at the same time.

if Expression1 or Expression2:
    print("we use the or-condition")

if answer == "Yes" or answer == "yes":
    print("You entered Yes...")

The second example becomes handy when you want to let a user be more flexible, you will allow “Yes” and “yes” as an answer to a question, you’ll try to implement this in your program too with the exercises.

Python for-loop – loop through exercises with

Now let’s get back to our program, and look at the first branch i.e. the boolean expression where the user type “Yes” – we’ll introduce the concept of loops now. Remember, the program should display all exercises, according to the question presented to the user

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

if response == "Yes":
  print("Here are all the exercises:")
  for exercise in exercises:
    print(exercise)

Notice the construct: keyword for followed by a variable, followed by keyword in followed by a variable (a list or tuple).

for variable1 in variable2

This tells the program to loop through each element in a data structure (like a list or tuple) and execute the code in the loop for each individual element. For our program, it will print each exercise on a separate line, and the output should look like the following. Run the program and confirm you see the same.

Bench press
Deadlift
Squat
Biceps curl

On each iteration print(exercise) works because exercise is bound or assigned the value from the tuple, one value at a time.

In this example:

  1. Starting the loop: for exercise in exercises means that Python starts going through each element in exercises.
  2. Assignment of exercise : For each iteration (loop), exercise becomes the name of one exercise in turn, from ‘Bench press’ to ‘Biceps curl.’
  3. Executing instructions: The code in the loop, print(exercise), is executed each time the loop repeats. So each exercise is printed on its own line.

Insert another statement inside the for-loop block, right above print(exercises) and see the result. Don’t forget to add same indentation.

How many iterations does the loop run?

It depends on the number of elements in the list – the purpose of a for loop is to go through all the elements in the list. The answer is len(exercises), try printing it after the loop.

print("The length of exercises is ", len(exercises))

Alternatively, imagine if you had a really long list, you’d have to print each exercise on its own line. Something that would become cumbersome quickly.

if response == 'Yes':
    print(exercises[0])
    print(exercises[1])
    print(exercises[2])
    print(exercises[3])

Now you see the purpose of the the for loop to handle the list (or tuple) efficiently. So, if we had 10 exercises, the for loop wouldn’t change at all. However, you’d have to add 6 more rows of print, which one is better?

Remember a for-loop in Python is a powerful tool for repeating instructions multiple times – perfect for lists and other collections. Using for-loops, we can work efficiently with collections of data and make the program more flexible. Feel free to add your own instructions inside the loop to experiment with how you can handle each element in a list.

if response == 'Yes':
    print('Here are all the exercises:')
    for exercise in exercises:
        print(exercise)
elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

Use the operator “in”

Python has a neat operator we can use called in. Let’s demonstrate how to use it in our program. Extend the program by adding a new question asking the user which exercise details to display. In programming terms, we want to search the tuple exercises for a value, namely the exercise the user type into the program dialogue.

As a result, we’ll just print a generic message for each exercise. Add the following after the code above:

selected_exercise = input('Which exercise would you like to know more about? ')

if selected_exercise in exercises:
    print(f'You chose {selected_exercise}. This is a fundamental exercise for building strength.')
else:
    print('That exercise is not in the schedule.')

Here, we use in to check if the exercise entered by the user exists in exercises. If it does, we display information about the exercise; otherwise, we inform the user that the exercise isn’t in the schedule.

The complete program code

week = 1
schedule = 'Workout A'
exercises = ('Bench press', 'Deadlift', 'Squat', 'Biceps curl')

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

if response == 'Yes':
    print('Here are all the exercises:')


elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

    selected_exercise = input('Which exercise would you like to know more about? ')

if selected_exercise in exercises:
    print(f'You chose {selected_exercise}. This is a fundamental exercise for building strength.')
else:
    print('That exercise is not in the schedule.')

Exercises

  1. Extend the exercises tuple with more exercises.
  2. Improve the exercise details, by creating a different messages for each exercise. You’d need to write an if-statements inside an if-statement.
  3. Extend the if-statement to for the word No, with both uppercase and lowercase “N”. The user should be able to enter either “no” or “No”.
  4. Extend the if-statement in previous exercise to allow more alternatives, e.g. “Nope”, “Nah” or whatever you can think of.
  5. In the next part, we’ll use a dictionary to store descriptions for each exercise in a cleaner way.
  6. Another loop is the while-loop, go to docs.python.org to find out more about it. Use the function len() to determine the condition.

Terminology

Review these terms

  • tuple
  • list
  • if-statement
  • for-loop
  • boolean expression

Summary

In this part, you’ve seen how to use the if-statements in order to handle different scenarios in your program. It allow your program to become more interactive, but also handle things in the code to work according to your plan. Being able to create different options and decision paths in a program is an important part of programming. This makes programs more dynamic and user-friendly.

In the next part, we’ll dive deeper into working with loops and explore dictionaries.

If you’ve missed the previous post, check it out Python if-statements – beginning the training app

See you in the next section!

How To Install Python On Your Computer

Installing or updating Python can sometimes be a little tricky and it’s confusing to understand which version is actually installed. Don’t worry in this tutorial we show you how to handle that. One of the downsides of Python is setting up the environment in a correct way and the fact that there are a multitude of installation methods can make the beginner unsure about which Python version is installed.

If you install Visual Studio Code it cannot guarantee that your configuration is in the right place when the time comes to code and run your scripts.

Common ways to install Python

You can download official Python distributions from Python.org, install from a package manager, and even install specialized distributions for scientific computing, Internet of Things, and embedded systems. 

This tutorial focuses on official distributions, as they’re generally the best option for getting started with learning to program in Python.

In this tutorial you’ll learn how to:

  • Check which version of Python, if any, is installed on your machine
  • Install or update Python on WindowsmacOS, and Linux

This is different depending on your operating system. There’s also the option of using Anaconda or even pyenv.

Depending on your use case I’d recommend different options.

Install Python as a beginner for the first time

This method is common for beginners and applies regardless of operating system you are running. The process the most recognizable for newcomers and is highly recommended.

  1. Go to python.org/downloads
  2. Select the correct version for your operating system. The site should handle it automatically for you. It will look something like the following

Proceed to installing and following the default instructions of the installer.

If you are on Windows, then go to the Start Menu and search for “IDLE”. That should start the default Python interpreter window.

If you are on MacOS then use Spotlight (Command + Space) and search for “IDLE”. Or use Finder to go to Applications -> IDLE

If you are on Linux then you probably need to unzip the artifact/package just downloaded, or in the best case the installer is ready made to just double click.

If you are using Linux

If you are following from the section above, and you are not able to double click the package, then you must probably unzip the package with a tool like, tar, bunzip, gunzip.

If you’re diving right into the terminal, lets first of all check which Python version your Linux distribution comes with.

Sometimes you may have python, python2 or python3 command available, or sometimes all of them. You can check the system Python version as the following

$ python --version

$ python2 --version

$ python3 --version

If any command gives an error, then you don’t have that version installed.

Easier would be, if you type which python then your terminal will show which binary is executed and linked to that python command — given that it exists on your system of course.

If you are using Ubuntu then go ahead and do the following.

$ sudo apt update
$ sudo apt install python3

If the above raises an error, then you need to find which Python-version exists in your package manager and use that when you install. First search for the correct name like this.

$ apt search python

If you are using Windows

Installing on Windows can get a bit complicated, but this guide will hopefully sort things out for you. The most simple method is to go to http://python.org/downloads and download the latest Python version for Windows. If you’re just a beginner then Windows also offers a very simple method through their Microsoft Store. None of these steps below are necessary if you followed the steps in the first section of this post

Install Python via The Microsoft Store method

Open up Microsoft Store and search for Python. Select the latest version and install it.

Do you already have a Python version installed?

  1. Open Powershell by going to Start menu
  2. Type in PowerShell, see screenshot
  3. Type the following in the new PowerShell window: python --version

If you don’t get an error from the last step, then you should see the Python version installed on your Windows system. In this case you don’t need to do anything more.

Step 1 – Locate and open PowerShell

Step 2 – Check Python version if it’s installed

Step 3 – Decide installation method

If you don’t have Python installed already then go ahead and either download Python from the official website or the Microsoft Store

Step 4 – Open up IDLE

This step is the same as earlier, you can start the IDLE program by going to the Start menu and typing “IDLE” like the screenshot below. You see that I have several versions of Python installed at the same time, this is not a problem at all.

EXTRA – Try online editors for Python

You can also try to experiment with Python without installing anything on your computer. Click the following site for example

https://www.python.org/shell/
https://repl.it – advanced

Python and the Building Blocks of Programming

Python and the Building Blocks of Programming

Goals of This Post Series

  • You will learn the anatomy of a program and what a typical Python program consists of.
  • Introduce variables, data structures and functions as basic building blocks of a program
  • Introduce classes and objects as advanced building blocks of a program.

Each building blocks can be used in different ways, and not all of them are required in a single program. Using these blocks, we can gradually construct our program in different ways until we achieve the desired functionality.

By the end of this post, you will have a first introduction of what constitutes a basic Python program by understanding what variables are.

In the next post you will be able to create interactive dialogues with users and store information in variables and data structures.

Data handling is a fundamental of any program so it’s important to understand this early on.

Building Blocks of a Program

Every program is made up of one or more building blocks. We will explore all of them in a series of posts in this blog.

  • Variables
  • Data Structures
  • Functions
  • Classes

programming_building_blocks_blog.jpg

Examples of how building blocks are used

Each building block serves a specific purpose, categorized into storing information (data) or processing it.

Examples of processing information could be:

  • Calculating VAT given a price.
  • Determining loan costs based on loan amount and interest rate.
  • Extracting parts of speech (e.g., verbs, nouns) from a long text or simply calculating the text’s length.
  • Calculating age based on a birthdate.

Examples of holding (storing) information could be:

  • Storing personal details throughout a program
  • Storing account balance
  • Storing textual information about a book or news site

Here’s an example of some building blocks in a program, feel free to try it out in your Python environment.

Have you not installed Python yet? Check out the simple guide we have

How To Install Python On Your Computer

Building block 1 – Variables

For the examples in this post, it’s sufficient to write them in IDLE. However, if you are already familiar or prefer VSCode, PyCharm or another editor, feel free to do so.

Each file you create are called a module. You may encounter both when you read online resources.

To create a new file in IDLE, go to File -> New File. Name the new file building_blocks_ex1.py.

idle_newfile.JPG

You will see an empty window where you can write your code. Paste the following code and then go to Run -> Run Module.

name = 'Karl'
direction = 'North'
cost = 200
print(name)
print(direction)
print(cost)

The example above demonstrates a short program showcasing variables, assignment, and output. The left hand side is the variable name and the right hand side is the value assigned to that variable.

A variable is a container to store data in your program.

Python has many built-in functions that we will use, one of them is the useful print(). That will output to your window the result of each variable we created: name, direction and cost.

Exercise

Practice writing your own variables. Notice the following

  • What happens if you change single quote to double quotes?
  • Can you change cost to something other than a number? Like a name?
  • Create a new variable and name it, e.g. salary, age, points – use your imagination!
  • Print the newly created variable(s).
  • What happen if you combine the print like so print(name, direction, cost)?

This was a short introduction to variables and already in the next post we will build on this to interact with a user.

Host your Discord Bot – 3 popular options

Having your own Discord Bot can be a nice way of adding a custom experience to your users on the server. In order to host your Discord bot, a maintainer has a couple of options to look at before deciding which is the right one. Along the way, there are also a couple of things to take into consideration when you want to host a Discord Bot on your server. You can first of course look if your needs are met by a bot from https://top.gg/. Otherwise you can write your own and for that there are more things to consider.

What to Consider

  • Which language is the bot written in?
  • How do you want to host it? What matters to you?
    • personal support
    • uptime
    • monitoring

There are popular languages to write your bot in, some of the popular are

  • Java
  • Python
  • NodeJS.

Host options for a Discord Bot

The common ways to setup a Discord Bot can be

  • VPS on your own
  • External hosting provider, in fact that’s exactly what we can help you with. Check out our process and pipeline for deploying the Heaplevel Discord bot here.
  • Locally on your desktop

Let’s start with the first one VPS. How is the process to get the bot up and running usually?

Discord Bot Hosted on a VPS

  1. Setup VPS by registering a new account at a hosting provider
  2. Login to the VPS and access the terminal
  3. Install the programming environment necessary. This depends on which language you have written your bot in. It could be Python, NodeJS, Java or anything else.
  4. The code. You need a way to transfer the code to the actual VPS machine. Either it’s on a code repository like Github or Bitbucket. Or you can transfer it via some UI file manager. Check with your provider.
  5. When you have the code locally, it’s smart to test run it. this step verifies that you have all the necessary tools for your bot to run. How you do that depends on your code base again. This is probably something you’ve already tried when developing the code locally on your own desktop machine.
  6. If you have verified the code works then it’s time to setup the code to run your server. You can either run your main file as a standalone process, setup a cronjob or write a containerized version of it (link to Docker article – How to run a Docker discord bot).
  7. This step is ususally skipped but if you have the chance to monitor the resource usage on the server it’s a major plus.
  8. Handle updates to the code
  9. Handle bot crashes – due to usage utilization or anything else

With these things we can also support you if you run into problems.

Discord Bot hosted on a external hosting provider

While the registration part is usually the same as for VPS, the real advantage is that an external hosting provider will provide you with an interface for uploading your code and run it. Usually there is an amount of support included in your account. A good hosting provider will allow you to just point to a repository on GitHub or BitBucket for example instead of you manually uploading the files to the server.

The steps are usually

  1. Register your account with the Discord bot hosting provider
  2. Upload your files
  3. Start the bot through the provider’s integrated interface

Discord Bot locally on your desktop

Let’s say you have a little desktop machine laying there without a purpose, you can use it as your local little server. This scenario can look different depending on your setup. But it’s closest to preparing your VPS for Discord Bot. You will need the following

  1. Development environment for the language the bot is written in
  2. Some scheduling and monitoring mechanism if the Discord bot will crash.
  3. If you are sure that everything is complete, then you can run the bot through the development environment on the desktop computer.

Summary

We have looked at different options for setting up your Discord Bot. While they look similar, the decision boils down to what’s important for you. The requirements you have will differ to somebody else. Some are happy with no support from their provider while others are happy to outsource that task to someone else. You still need a fair amount of knowledge to setup the Discord bot on the underlying system, usually in Linux you require a little more experience.

If you find yourself in need of discussing this with us then it’s something we can provide support for. Even if you have support from your provider, drop us an email.

How to open a file in Python in different modes

Opening a file in Python is really simple. How do you create a file though that doesn’t exist?

If you use the open function in Python like so

open('file.txt')

You’ll run into the error

FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

Mode for open a file

We need to understand that opening a file can be followed by a mode parameter, the signature for the function is open(file, mode).

If you only submit the filename the default mode is set to ‘read’ mode. Which only makes sense if the file exists. Here are the other modes

  • r – open for reading (default)
  • t – text mode (default)
  • w – write mode
  • a – append mode
  • x – open file, failing if the file already exists
  • b – binary mode

Open and create the file

Referring to the above table, we can use different modes for creating a file for the first time. Depending on our purpose if we want to delete an existing file with the same name or not.

Let’s try this

file = open('file.txt', 'w')
file.write('First line')
file.close()

Do you want to know more about a Python topic? Contact us or leave a comment below :).

Getting started with Javascript

If you want to start programming in Javascript you might ask where do you actually start?

It might be that you’ve been interested in learning more about web programming in general, for which it would be useful to also learn about HTML and CSS as well. While HTML and CSS deal with the structure of a website, Javascript adds the dynamic flavour to your website.

There is also a possibility that you want to learn Javascript to write backend applications, using NodeJS. The applications for Javascript are several, both websites and web applications can use Javascript.

If this is the first time to Javascript you can start by learning about the language itself and start play around in a sandbox environment. That is the best option to learn Javascript.

Learn Javascript by examples

We will experiment with Javascript by looking at some examples. This guide is for you that have a little programming background.

  1. Navigate to JSFiddle
  2. Copy the following code in the HTML box
  3. Hit the Run button. You should see a popup displaying the text “Hello, world!”
<!DOCTYPE HTML>
<html>
<head>
<script>
    alert( 'Hello, world!' );
  </script>
</head>
<body>
  The body
</body>

</html>

So what did we actually do here? Simply explained we used the Javascript function called alert to write a message in a popup box.

Go ahead and create a second alert with a new message. After you hit Run you should have two popup boxes with two different messages.

How to setup Matomo with MariaDB on Docker

$ docker run --name matomo-mariadb -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mariadb:latest
$ docker run -d --link matomo-mariadb:db -p 8089:80 -p 3306:3306 matomo

This will spin up a Matomo instance on MariaDB running on the default port 3306. You can then access the Matomo instance to continue the installation by navigation to your hostname:3306. E.g. if you’re running this on your VPS it will be your http://<VPS IP>:3306

http://localhost:3306 if you’re on your local dev machine.

The above will not persist your data, in order to do that you need to use volumes on Docker. So if you plan on restarting your Docker container (likely) then you should use volumes. Otherwise when you restart the Docker container you’ll have to reinstall the Matomo instance.

docker volume create matomo-vol
docker run -d --link matomo-mariadb:db -p 8089:80 -p 3306:3306 -v matomo-vol:/var/www/html matomo

Javascript true and false values

In Javascript comparing values are not always as straightforward as one would expect. Overcoming that fear of which variables are truthy are sometimes is just as easy as learning which values are falsy. If you remember them (6 values) then you can easily know which values are true.

  • NaN
  • false
  • undefined
  • ”, “”, “ – the empty string either single quotes, double quotes or template literalts
  • 0
  • null

How do you remember these 6 falsy values in Javascript you say? People remember things differently and since all are unique there are many ways to remember.

Remember the simple things first, the one number i.e 0 (zero) is always false. That’s easy to remember right? Also false makes perfect sense to be…you guessed it: false.

So four values to go, look at this: null, NaN, undefined

Finally strings contain text, strings talk, but a string that doesn’t contain anything can’t talk, so it should be false.

The perfect order

  • 0
  • false
  • null – NaN – undefined — becomes nullnandefined – null (and) undefined. Those are three values coerced into one to remember easily!
  • empty strings – can’t talk, should be false then. ”, “”, “