LEARN PYTHON: CHAPTER ONE

Learning Python has never been easier, but really learning any programming language has been considered difficult, maybe at times even considered to be “Rocket science”. But the reality is that Programming is really just automating repetitive tasks that consume a lot of time and become quite the annoyance. The evolution of such things are when we find websites like Facebook, or Twitter, or Google. These are all nothing but more complex versions of automated tasks.

Most programming courses always start with Hello World as an example, but do you understand why you are doing this task? Many times I’ve often found myself struggling to grasp programming concepts not because I wasn’t smart enough, but more because I was not understanding the “why” behind it all. I think a lot of individuals also experience the same struggles with programming.

You have to understand in any capacity, “why” you are doing something. So instead of us starting off with “Hello World” and telling you that you’ve successfully programmed your first application, I’m going to explain to you “why” you need to write such a thing.

GETTING STARTED

For the majority of this course I will be trying to focus and emphasize on some a few of the things I have listed here:

  • Best practices
  • Latest techniques
  • Latest version of Python 3 (3.9.7)
  • macOS or Linux (These days Ubuntu is fairly easy and straightforward to setup)
  • Tools and system requirements for all of the above

I don’t want to bore you too much with details, but we need to take sometime before we start actually writing code and running out code successfully – If you feel you have a good feel for this, then feel free to skip ahead, or skip this chapter altogether.

REQUIREMENTS

If you are on macOS (mojave or better), then most of your work has already been accomplished. What we need to do is install and download Homebrew, and make sure our python and pip is installed and up-to-date. If you’re on a Linux computer, lets open up your terminal by pressing Alt+T on the desktop. If you’re on a macOS computer, press cmd + spacebar and type in terminal, then press enter to open it.

For macOS:

  • Visit https://brew.sh and copy the following line of code and then paste if into your terminal
  • /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  • After it has installed, run brew install python3 which should install both python3 and pip3
  • Confirm your versions with python3 --version and pip3 --version
  • If necessary, you made need to setup a root account on your macOS machine

For Linux:

  • Open your terminal
  • Type in sudo apt-get update && sudo apt-get install python3 python3-pip
  • Once you have done both with no errors, type python3 --version and you should see Python 3.9.7
  • Type in pip3 --version and you should see pip 21.2.4 from /usr/local/lib/python3.9/site-packages/pip (python 3.9)

After you have successfully completed the requirements, it is time to write and execute your first piece of code. Open up your terminal again, and type in cd ~/ then run mkdir robs_python_course then cd ~/robs_python_course you can also press tab while you’re using the cd command for word completion. Once you have cd’d into the directory we want to create our python script, so run vim myscript.py and then press the letter i key on your keyboard, and then simply copy and paste the code below. You can save your changes by pressing the escape key, then :w and then :q this will write and quit your file. Also, remember that each time you are indenting code, you must have only four spaces, tabs don’t work and may cause your code to error out.

Once you have done that, you can run your script with python3 myscript.py and see how it executes.

#!/usr/bin/python3
import os

def main():
    print("Hello World\n")


if __name__ == '__main__':
    main()

Why the hell do I need to know how to print Hello World? Please get me out of Hello World hell. 😖

Breaking Things Down

Let us break down this code line by line, I’ll make it fast for you so that we don’t get bored in the details. We first use the hash bang statement which points to /usr/bin/python3 the reason we do this is so that we can run our Python script when we convert it into an executable file. In Linux, Unix, and macOS systems, a file can be converted to an executable with the command sudo chmod +x /path/to/your/file Once your file has been made an executable, it can be ran such as ./myPythonFile.py instead of the traditional python3 myPythonFile.py It makes things a little easier and can also be moved into /usr/local/bin/myPythonFile or /usr/bin/myPythonFile and you can run your application such as myPythonFile without any other special characters (It must be an executable before this works).

More on this later, but if you’ve been keeping up so far we can continue, of course I will explain this in further detail in another post.

Import Statements

Python shares similar functionality to other languages, some languages can “include” other packages that were created by other programmers or companies; it is much easier to consider these as “libraries” that contain special functionality which your code can inherit from. In this case, import os allows us to import many of the OS functions that have been prebuilt for use within the Python programming language. A good simple example of this is when you would like to use an environment variable declared within your system, but don’t want to code that functionality from scratch. After using import os this task can be accomplished with the following statement in your Python code myVar = os.getenv("MyEnvironmentVariable") your variable myVar will retrieve the value that is stored within your system environment variable MyEnvironmentVariable. This makes it easier to do a number of things like storing usernames, passwords, API keys, etc… without exposing them to the outside world, it allows you to code a little more securely and professionally.

#!/usr/bin/python3 

import os

def main():
    """
    declare a variable in python, and give it the value 
    of your stored env variable in your terminal
    """
    myEnvironmentVar = os.getenv('myEnvironmentVar')
    
    # print out the value or contents of our stored environment variable
    print(f"{myEnvironmentVar}")

if __name__ == '__main__':
    main() 

A few new things have been introduced here, first being comments. Comments can be made in your Python scripts with the """ """ or a # symbol and Python will ignore it, this is useful to document and keep track of your code and functions, as well as make it easier for other programmers who work on your code.

The next piece of code is the environment variable we declare, now typically in a terminal prior to running your Python script, you can declare environment variables. Go ahead and try it, open up your terminal and type myEnvironmentVar="Hello there!" – or you can type export myEnvironmentVar="Hello there!" – after that, let us create the script above in the same way we did previously, but save it as a new filename. Once you have exported your variable, and saved your file, go ahead and run sudo chmod +x yourFileName.py and then ./yourFileName.py – if everything was written and saved correctly, you should see the output “Hello there!”

Finally, this works because of the variable we associate in python, and the new formatting feature we have introduced into the print functionality. Previously, printing the contents of a variable was formatted differently, but in Python 3+ variables can be printed with print(f"{my_var}") and you can extra what is contained within that variable.

Pretty powerful eh? There are many common variables stored in your terminal by default when launched, you can see what these variables are by opening your terminal and running the command env. Typically some output is available – play around with this by changing myEnvironmentVariable = os.getenv('myEnvironmentVariable') to something that is in your terminal like:

myEnv = os.getenv('HOME') – for me, I get HOME=/home/robmcelvenny printed out for me. You can see why this is powerful, variables can be stored and accessed without exposing them to any prying eyes, securely, and functionally. This comes in handy when we work with APIs over the web, and can also extend to other tools and systems beyond just programming.

MAIN Function

The main function that you see here is responsible for running any code written after def main(): In this example main doesn’t take any additional parameters, we’ll get to parameters as we get more familiar with the code, but in the short term just understand that main will run when it is called on line 7

if __name__ == "__main__": 
    main()

This example helps us keep our code much more modular, so we can stay organized as well as reuse functions as we build our code.

So there you have it, the first chapter in your journey is complete. Next we will be learning more about variables, types, commonly used tasks, and how we can leverage our programs and scripts to make our lives easier. If you have any questions, suggestions, or just want to chat, feel free to leave a comment. Enjoy your day 🤝