So I love programming, and it doesn’t take long looking at this blog to know that I love coding. A few years ago, I got put on a team where I was tasked with building a solution using predominantly python. Now the fun part about that was I had never written a line of python before. So this created a whole new world for me.
Now I will say Python is one of my favorite languages to work in. I really enjoy how easy it is to get started developing python, and how flexible the language is.
So what do I need to get started?
So what do I need to get started with python? There are a few things that you need. First and foremost, you need a computer to do development on. I generally don’t recommend an iPad. I would recommend a desktop or a laptop. From there, you really need the following:
- An IDE (Development Environment to work in)
And honestly that’s about it. It really depends on what you want to do. Now the good news is that there a great IDE you can use called VSCode.
VSCode really is the default tool for working in code, and part of the reason why is that it enables extensions so that you can use it to work on anything.
Some of the best extensions you can use are:
From there, you need to install python to work with it. There is a fantastic article of the options to install on windows found here.
If you are installing Python on WSL, you can run the following commands:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python3
python3 --version
Why do people use Python?
Honestly there are about a million answers to this question. But if I had to boil down why I think it’s so popular, the reasons would be:
- Low Barrier to Entry: Honestly like I said above, I download a free tool, install a few free extensions, and I’m off-to-the-races. Python is very easy to pickup and start working with.
- It can be used for almost anything: Python can be used for working with data, building AI models, process automation, robotics, and even web page development. The fact that I can learn one language and work in a wide variety of things makes python a really popular language to work in.
- Lots of Open-Source tools and modules: You name it, there’s packages and libraries that can be installed to help. This makes it very easy to interface with a wide variety of tools and systems.
- Values convention over restriction: For lots of programming languages, there’s only one right way to structure your code to make it work. Python is generally laxed with these kind of rules and gives you the freedom to structure your code in the way you want to make it effective.
How do I structure my code?
As mentioned above, python is pretty easy to structure code. You start by creating a “.py” file to run, and then run the code. Take this as an example, if this is your python(.py) file named “hello-world.py”
print("Hello World")
If you then open a terminal in VSCode, you can run the following command:
python3 ./hello-world.py
And it writes the output to the terminal. Congratulations that’s all it took to get a python app built. Now I’m betting like me, you want to do much more than that.
So let’s try something a little more complicated. Go ahead and create a file in the same directory as your “hello-world.py” file, named “names.json.” The contents should be this:
{
"name":"YOUR_NAME_HERE"
}
Now update your “hello-world.py” to have this:
import json
# Read the JSON file
with open('./name.json', 'r') as file:
data = json.load(file)
# Pull the "name" property
name = data.get('name', 'World')
# Print the greeting
print(f"Hello {name}")
And you can run this code with the following command:
python3 ./hello-world.py
Notice how your code now reads the contents of the json file and plugs the value in. That’s probably the most simple python app you’re going to write and I hope you write a lot more :).
Now if I want to encapsulate my code, I can put that code into a class, which makes a reusable object that can be called within my code. So if I wanted to create a class to wrap this code, and call it “HelloService”, I could do that by creating a new file called “HelloService.py” and make the contents be the following:
import json
class helloservice:
def __init__(self, path : str = "./name.json"):
self.path = path
def Load_File(self):
# Read the JSON file
with open('./name.json', 'r') as file:
data = json.load(file)
self.name = data.get('name', 'World')
def SayHello(self):
return f"Hello {self.name}"
NOTE: Python cares about case (“num1” and “Num1” are not the same) and it cares about indentations for structure.
Now in the above class, you will notice the “init” method, which is the constructor for the class, and everytime you see me make the reference of “self.path” that’s a property called “path” that can be used in other methods.
And then in the “SayHello” method, I am returning a value.
Now if I update “hello-world.py” to the following:
from HelloService import helloservice
hello = helloservice()
hello.Load_File()
hello_response = hello.SayHello()
print(hello_response)
Now above, I mentioned “modules and libraries” for python. And the question is where do those come from. The truth is that when we added that “import json” line above, we were pulling in the json library which has the code for reading json files. That library comes pre-installed with python. But what happens when we want to install modules that don’t come by default with python.
The truth is that PyPI, is the internet’s repository for python modules. In many cases these modules and libraries can also be hosted on private sources, but there’s a lot on PyPI to start with. So the question becomes how do we install modules from it.
Now you can install modules using “pip” command, and usually people will add a list of these into a file named “requirements.txt”.
For our sample application here, we are going to add a web api that can be called to hit our class. To do this, we are going to create a file in the same directory as our other files called “requirements.txt” and the contents are going to be:
Flask
And then run the following command to perform the pip install:
pip install -r requirements.txt
If you get an error that “pip” is not installed, run the following:
sudo apt install python3-pip
And then we are going to update our hello-world.py to have the following:
from flask import Flask, jsonify, request
from HelloService import helloservice
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello():
hello = helloservice()
hello.Load_File()
hello_response = hello.SayHello()
return jsonify(message=hello_response)
app.run(debug=True, port=5001)
We can then run our application:
python3 ./hello-world.py
And you should see the following:
* Serving Flask app 'hello-world'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5001
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 111-222-520
Now, if I open a new terminal window and run the following command, I can call our API and get a response.
curl http://127.0.0.1:5001/hello
And I will get back this:
{
"message": "Hello Kevin"
}
Where can I find some good resources?
So if you want to learn more about python, I recommend the following resources:
- Python for Beginners: Python.org: The documentation from the source on using python. A great place to start.
- How to use Python: Your First Steps (RealPython.org): A great article that provides a lot of good documentation on coding concepts.
- Python for Data Science: Good article with a data science bend on getting started with python.
- VSCode and Python Tutorials: A great article and tutorial with VSCode.
- Python and Raspberry Pi: A great article on getting started with Python and a Raspberry Pi, which gets into the world of robotics and automation.
- Python and Ardunio: A great article about Internet-of-things and Python.
Good videos:
A great video to get started.
A great video for learning the basics.