LEARN PYTHON: CHAPTER THREE

L

Previously, I wanted to get us familiar with data types, variables, and how things work in Python. Even a little bit on setting up an OK development environment. Now we can move on to a little bit of more complicated thing. The next few chapters are going to be taking you deeper into some projects, as well as system related tasks; this way you could get a good handle of why you need Python. I hope to make this as quick and easy for you so that we can get working on some projects.

You can run the examples below by creating a new .py file, then saving it, and sequentially running python3 my_saved_file.py

Variables

Variables are used to store values that can be used throughout the code.

Variables can also be passed into functions, they can also have data statically or dynamically updated.

#!/usr/bin/python3

myVariable = "My stored value"

print(myVariable)

Arrays

Arrays are a way to store multiple values in a single variable name.

Values that are stored within an array are indexed from the number 0 and each subsequent value is 1, 2, 3, 4, etc… They can be accessed with its index number, e.g. myArray[0] for the first value stored, myArray[1] for the second, and myArray[2] for the third. So on and so fourth.

#!/usr/bin/python3

myArray = ["some value", "another value", 20, "yet another value"]
print(myArray)

# We can also print the individual values
print(myArray[0], myArray[1], myArray[2])

# We can also loop through the values
for val in myArray:
    print(val)

Loops? Whats that?

– You … me … ok at least thats what I think you’re saying!

I haven’t brought about Loops yet because I am going to be saving that for Chapter Four of this “book”. Anyway, to make things short and simple, a loop will allow us to loop through all the values in an array. Loops are not limited to just Arrays, but that is the fastest example I can give you. You might be wondering why you would want to loop through an array, but think of it as saving yourself time and preventing yourself from doing a task manually, over and over again. Remember, it is about automating repetitive tasks, so Loops will be a very important part of our toolset.

Dictionaries

Dictionaries are a collection of key-value pairs. The keys are used to access the values.

Dictionary’s give us a bit of flexibility when it comes to storing values. So far you’ve learned about Variables – and how Arrays are just variables that allow us to store more than one value. Dictionary’s allow us to store keys and values, and when we use that key, we can retrieve the stored value in return. It might seem a little arcane at first, but once you understand whats happening under the hood it becomes easier!

#!/usr/bin/python3

# Dictionary with keys and values
myDict = {
    'myKey' : 'someValue',
    'myKey2' : 35,
    'myKey3' : 4.5
}

# Accessing a dictionary's values
myDict['myKey']
myDict['myKey2']
myDict['myKey3']
print(myDict['myKey'])
# Multiplying values from your dict
someMultiplication = myDict['myKey2'] * myDict['myKey3']
print(someMultiplication)

The great thing about Dictionaries is that your keys can return different values, regardless of their data-type, you can also manipulate these values, and even add to, or subtract from the dictionary. It depends on what kind of data you’re working with and the result you’re expecting. Though, you can multiply myDict['myKey1'] * myDict['myKey2'] (Python has a shortcut to repeating strings by multiplying it times a number) You cannot add a string and an int together. I don’t see much use case for this, but it is important to understand. 💯

JSON

JSON is a data interchange format. It is a text-based format that is used to exchange data between programs.

JSON stands for Javascript Object Notation, and is by far one of the best parts of programming these days. Much software, websites, databases, all use JSON as the format is so easily interchangeable between systems. When the time comes, you will start to see the bigger picture when writing software in Python. Similarly, the way JSON is stored is in the format of a dictionary of keys and values, and you can also create JSON from a dictionary, and create a dictionary from JSON. For now, this topic is so large – I can’t quite possibly fit it all into one post, but to give you a small example of it

#!/usr/bin/python3 

import os
import json 

# Storing JSON and printing or dumping the results in a neatly formatted way

myJson = {
    "name": "John",
    "age": "30",
    "city": "New York"
}

print(json.dumps(myJson, indent=4))

# Accessing a value by key

print(myJson["name"]) 
print(myJson["age"])

Pretty cool right? JSON is also at the centerpiece of APIs (Application Programming Interfaces), in the past, many of these key-value pairs were encoded with XML. XML, although very useful, was extremely hard to read and it wasn’t very user friendly. JSON makes APIs a little easier to understand when querying information found across the web. Say you want Weather information from a website like weatherunderground, you can query their API for a specific city and state, and it will return all of the information back to you at high speeds in JSON. Because it is JSON it makes this information travel back to you much faster than other data formats.

Functions

Functions are used to perform a specific and repetitive task.

Finally, before we start Chapter Four (Which will cover functions with some more depth) I wanted to briefly overview, how all of what we spoke of in this post can work in functions. Variables, Arrays, Dictionaries, JSON and more can all be passed between functions.

#!/usr/bin/python3

def myDivideFunc(myVal1, myVal2):
    return myVal1 / myVal2

def myJsonFunc(someData):
    print(json.dumps(someData, indent=4))
    for key in someData:
        print(key)
        print(someData[key])
    return someData[key]
def main():
    dividedValues = myDivideFunc(5, 2)
    print(dividedValues)
    myJson = { 
       "name" : "rob",
       "location" : "earth"
    }

    myJsonValues = myJsonFunc(myJson)
    print(myJsonValues)

As you can see in the above, we can pass values from the main function into our own functions we just created. I know I briefly touched on this, but I wanted to show how passing data between functions isn’t limited to just variables, and that you can also return specific data from those functions and print them out to the console. In myJsonFunc(someData) we pass in our JSON dictionary to the function, and we print out the values just to see what happens, but then we also loop through the dictionary and we store the key for the dictionary in a variable called key.

After, we can see how we can retrieve the value of each key with the loop by calling our dictionary and the key. We then return each of those values back to main function with return someData[key] and print out the result of the variable that is calling / storing the function, effectively allowing us to manipulate the data in anyway we want.

You can see overall how powerful just even two functions with JSON data and data in general can be. Depending on what we want to write, there is an endless world of real-world applicability within our cod and our applications. The only true limitations are our imaginations (and possibly our system specs).

So there you have it for this chapter, in the next chapter we will be focusing more on functions, loops, and even more built-ins with Python. After chapter four, we will be working on our first project so don’t forget to subscribe or sign up for future updates.

Keep it awesome! 👋

rob

Entrepreneur at heart, currently working on a social media site – I do DevOps consulting on my off-time so if you have some contract work you can contact me here. I currently work as a Site Reliability Engineer; My past work as a DevOps Engineer for a self-driving car company. When I'm not in front of a computer – I am at the gym or at the beach.

Social

ADVERTISEMENT

Don't miss out!

Don't miss out! Sign up to be notified when new content drops.