My Journey with Python (Part I)

M Yauri M Attamimi
13 min readJun 11, 2019

--

I’ve been working with Java for about 14 years now, and the last 2 years i’ve also worked with NodeJS and Golang to build some middleware AI platforms for my Startup. Nevertheless, i often push myself in learning other technologies as well. I’ve been learning Python these past few weeks. I was inspired by its concise syntax and the prominent feature that supports almost anything. You can use Python for any GUI and/or web development, operating system shell, data processing and analysis (data science), etc. Someone said that you can build the world with Python :-). Mmmmm, sounds interesting.

Since i believe that the best way to grasp the knowledge is to write what i’ve learned, so i’m gonna try here to write everything i know so far about Python.
I have read from different books and websites, here i’m trying to summarize within 3 parts everything i got from those different resources. Hopefully, you would find this article useful, especially for those of you who’s trying to learn Python in a crash course.

As the title implied, this is the first part of my journey, and I’m thinking to write my journey within these following series:

  1. Python 3 Introduction → you are here
  2. Python 3 more advanced concepts (coming soon)
  3. Develop and deploy your first microservice to cloud (coming soon)
  4. Python for Data Enthusiast (coming soon)
  5. Utilizing Generative AI (LLM) for building an AI-based application (coming soon)

and each series contains several sections. However, please note that those aforementioned series can change anytime since i’m still on my journey in learning this platform now. So, most likely i will add other parts during my journey.

Python 3 Introduction

This section will contain these following sections:

  1. What Python is and which version should i use ?
  2. Installing Python
  3. Package/Module (dependency) Management
  4. What IDE (editor) to use
  5. General Syntax and Semantics
  6. IO Operation in Python
  7. Package and Module System in Python
  8. Best practice to start/manage your project
  9. Sample Console App

Enough the chit-chat and lets start with the first section :-).

What Python is and which version should i use ?

I won’t go details here since you can find many articles that explain about this. Shortly, i’d like to say that for those of you whom just started to learn python now (as i do), better to use Python 3 since it is the latest version and widely used now.

Installing Python

I believe that there are many resources out there to explain this installation process. So.. go ahead and grab it.

Package/Module (dependency) Management

Just like Java, Python also has package/module manager to install/import the module you need from the online repository. Even there are two tools you can use for this particular purpose (i.e. setuptools and pip), but I found that the easiest way to install the module you need was by using pip (i concluded that pip has superseded setuptools).

The pip is going to download the package from PyPI (Python Package Index), and then add it to your Python installation. From that point on, every Python script that you have on your system will have access to that particular package. Yet, please beware that different version can cause trouble to your application, especially if you have similar package (in different version) used within your different applications. For instance, lets say you have a complete web application using version 0.11 of Flask, and then you create another web application that is using version 0.12 of Flask. In this case, your second web application is running well, but unfortunately most likely it will break your older (first) application since it was expected to run with version 0.11 of Flask. You got the point right ? it would be ideal if you can install two different Flask versions for those two web applications respectively.

To address the issue of maintaining different versions of packages for different applications, Python has introduced the concept of virtual environments.
A virtual environment is a complete copy of the Python interpreter. When you install package in a virtual environment, the global (system-wide) Python interpreter is not affected, only the copy is. Therefore, the solution for you to have different package versions for different applications is by creating a different virtual environment for every application you have. Virtual environments also added the benefit that they are owned by the user who creates them, so they do not require an administrator account.

There are few ways to prepare your virtual environment. For me.. i used to prepare my virtual environment through these steps (all of the steps below were executed on the terminal) :

  1. Create your directory project and go into it.
  2. Create the virtual environment: virtualenv -p python3 venv
  3. Activate the virtual environment : source venv/bin/activate

That’s all :-). For those of you whom still a bit confused, i captured my screen as depicted below:

How to prepare your Virtual Environment

There are something that i’d like to highlight here. First, venv is the newly created directory that contains your isolated python environment (yeap, you’re right… this is your new virtual environment, though you don’t have to named it venv. You can give it any arbitrary name). Second thing, if you get an unrecognized command when trying to execute virtualenv, that means you need to grab it first through this following command from within your terminal:

pip3 install virtualenv

What IDE (editor) to use

There are many options for this one, but i would recommend either VisualStudio Code or PyCharm.

General Syntax and Semantics

Though you could find many resources about this one, but i’d like to recap some of those here. Hopefully, this will make you “dangerous enough” to start your journey as a Python developer after reading this blog series.

  • Basic Data Types

Python basic data types has nothing different with most basic data types in other programming languages. In general, you will find strings, numeric, and boolean values for Python Basic Data Types. Furthermore, numeric can be divided into an integer (int) and floating point (float). There is also complex data type (i.e. combination of real and imaginary numbers), but this kind of type is rarely used.

To define a string in Python, you can either surrounded it by using single-quote (’’) or double-quotes (””). Here’s the example:

hero = 'Yauri Attamimi'msg = "Yauri isn't coming today"

I’d like to explain few things here. First thing first, in order to define a variable in Python, you just need to specify a variable name (e.g. hero and msg) followed by an assignment operator (=) and the content/value of the variable.

Second thing regarding the above string definition, either way should be okay, yet sometimes it would depend on the content of your string value. For instance, in msg variable, we have enclosed the string value within the double-quotes (””) since the string’s content has a single-quote () in it.

Last but not least, important to know that Python is a dynamic typed (contrast with strongly-typed programming like Java), thus you can assign any arbitrary type to a variable. For instance, you can assign different types within one variable as you can see below:

Python is Dynamic Typed

Shortly, other types can be explained below:

# an integer value
rank = 9
# a float value
fee = 7500.50
# a boolean value (True | False)
# note the uppercase letter!
is_success = True
  • Operator

There are several basic operators in Python. I only show you here what are mostly used within your daily activities.

  • Composite Data Types

Python has 3 mostly used composite data types as described below:

""" List """
members = ["Yauri", "Azizi", "Fadzlan"]
""" Tuple """
members = ("Yauri", "Azizi", "Fadzlan")
""" Dictionary """
{
"id": 1,
"name": "Yauri Attamimi",
}
""" Combination of List and Dictionary """
members = [
{"id": 1, "name": "Yauri Attamimi" },
{"id": 2, "name": "Azizi"},
{"id": 3, "name": "Fadzlan"}
]

What make it different between list and tuple is that tuple is read-only (you can’t change once you created it), while list is writable thus you can modify the list with its built-in methods. Here’s the example:

# Define and yield a new list of members 
members = ["Yauri", "Azizi", "Fadzlan"]
print(members)
# append a new member into members, then yield
members.append("Joe")
print(members)
# remove a member from the list
members.remove("Joe")

You could find other list built-in methods from the Python 3 official documentation.

  • Iteration

There are 2 types of iteration in Python 3: while loop and forloop as described below:

# While Loop
x = 1
sum = 0
while x <= 10:
sum += x
x += 1
print(f'sum = {sum}')

as you can see, initially we defined a variable x with value 1, then we iterate through the while statement with condition x <= 10(i.e. the block statement inside a while will be executing repeatedly as long as the value of x is less than or equal to 10, thus you must not forget to increment the x value at the end of while block statement or else it will be looping forever). One important thing here as you might noticed already, In Python… instead of defining a block statement inside a curly braces ( { }) like in other programming languages (e.g. Java, C, etc), Python prefers to has an indentation over curly braces. That’s why you need to explicitly give an indentation to every statements that you’d like to put inside a block statement as shown above.

# For Loop
sum = 0
for x in range(1, 10):
sum += x
print(f'sum = {sum}')

for statement in Python differs from what you might used in other programming languages like Java. Python’s for statement iterates over the items of any sequence (a list or a string). Do you read it ? yes, a string. You can also iterates over a string or list like these:

# Iterates over a list
members = ["Yauri", "Wu Ji", "Oyama"]
for name in members:
print(name)
# Iterates over a string
greetings = "Good Morning"
for item in greetings:
print(item)
  • Conditional Statements

Perhaps, the most well-known and widely used for this kind of statement is the if statement as shown below:

# if statement
greeting = "Good Morning"
if is_morning:
print(greeting)
# if else statement
if is_morning:
print(greeting)
else
print("Have a good day for you!")
# if else if statement
if is_morning:
print(greeting)
elif not is_morning:
print("Have a good day for you!")
else:
print("I don't know what to say...")
  • Function

I believe that most of you know about function. Just to recap again, function is a block of statements (organized code) that is reusable, and is often used to perform a single action (it better be !).

Function provides better modularity of your application !!

Here’s how to define and calling functions:

def calculate_order(total_cost, shipping_cost):
return total_cost + shipping_cost

def print_total_order():
# call calculate_order function
total_order = calculate_order(2000, 75)
# print the result to console
print(f'Your total order: {total_order}')

# call print_total_order function
print_total_order()

As you see, you define a function by using keyword def. And the function body is written within a block statement (i.e. indicated by an indentation).

The naming convention used for a “function name” in Python is similar with the naming convention for a “variable name”, i.e. all written in lowercase, separated with an underscore (_)if has more than one word.

  • Exception

Exception is a way to catch any error thrown from your program. Your program might be syntactically correct, but sometimes error might happen within your program. Consider the following code snippet:

x = 2 / a
print(x)

if you run that code, and somehow a is equal to zero (0), then you’ll obviously get the following error:

and most of the case, the program will unexpectedly stop to run (crash).

In order to address that kind of situation, you’ll need to wrap those line of codes (which potentially cause an error) inside a try..exceptblock as shown below:

try:
x = 5 / 0
except ZeroDivisionError:
print('cannot divide a number with zero!')
else:
print(x)

So if you run the program again, it will nicely print a friendly message as shown below:

and the program will still continue running. Everyone is happy :-).

IO Operation in Python

There are many IO operations in Python, yet I will merely discuss here about input operation in the context of get an input from console and print an output to console, since this is what we need for our last section when we discuss about our console app application.

Read my short explanation below as usual (example of code):

# get a string input from a keyboard (within terminal)
name = input("Enter your name: ")
# print to console (terminal)
print(f"Howdy {name} !")

One important thing here, every input will be treated as a string by default, hence if you’d like to dealing with it in another data type such as an integer, you’ll need to cast the type as shown below:

# get an integer input from a keyboard (within terminal)
level = int(input("Enter your game level: "))
# print to console (terminal)
print(f"Game Level: {level}")

Package and Module System in Python

In Python, a sub-directory that includes a __init__.py file is considered as a package and can be imported. The __init__.py file is used to define what symbols are exposed by the package to the outside world. So when you import a package, the python interpreter will try to find and execute the __init__.py implicitly.

Here’s how to define a package (named utils):

as depicted on the above image, we also created file converter.py inside our new utils package. Here’s the source:

And here’s the various ways that can be used to import that particular package (hopefully quite explanatory for you ^_^):

# First Technique 
from utils import converter

print(converter.lbs_to_kg(165))
print(converter.kg_to_lbs(71.5))
# Second Technique
from utils.converter import lbs_to_kg, kg_to_lbs

print(lbs_to_kg(165))
print(kg_to_lbs(71.5))
# Third Technique
from utils.converter import lbs_to_kg as ptkg
from utils.converter import kg_to_lbs as kgtp

print(ptkg(165))
print(kgtp(71.5))

Best practice to start/manage your project

There are several best practices to maintain your project. First and foremost… as discussed previously in the point number three (package/module management), the best way to start your project is by creating a virtual environment for it, thus you’ll have a freedom to manage your package versions without affecting your global Python’s interpreter.

As you can see, you can use virtualenv command to create the virtual environment from within your project folder.
And since Python 3, there is a built-in virtual environment included. Thus, instead of using virtualenvcommand as shown above, you can also use this following command:

python3 -m venv myfirstp3env

Regardless of the method you used to create it from those aforementioned commands, you will have a virtual environment inside your project folder, which is represented as a folder with the name you’ve choosen before (i.e. venv in this case) where the virtual environment files are stored.

Note that in some operating systems you may need to use python instead of python3 in the command above. Some installations use python for Python 2.x releases and python3 for the 3.x releases, while others map python to the 3.x releases.

Once you have your virtual environment within the project, don’t forget to tell the system that you’re going to use it by activating it.

Activate the Virtual Environment

When you activate a virtual environment, the configuration of your terminal session is modified so that the Python interpreter stored inside the virtual environment is the one that is invoked when you type python. The terminal prompt is also modified to include the name of the activated virtual environment, i.e. (venv) p3journey1in this case. Note that all changes made to your terminal session are temporary and private to that session, so it won’t persist when you close the terminal.

After created the virtual environment for your project, the next point is to ensure that you manage your project source files in term of packages. So, the application will exist in a package. (See point number 6, Module System in Python).

Last but not least, if you were using other external libraries (other than built-in libraries from Python), don’t forget to freeze your libraries by using this following command:

pip freeze > requirements.txt

This will be listing all of your dependency libraries (incl. the version) within requirements.txt file. Consider this file same as a package.json (in NodeJS) or pom.xml (in Maven).

And don’t forget to skip/ignore your virtual environment folder from your repository. You can add/configure it by adding the folder name (venv in our case) into our .gitignore file (if you’re using Git).

That’s all of the best practices i found useful, at least for now :-).

Sample Console App

For our basic sample app, we’ll be creating a simple console application that asking a user to enter some basic informations such as their first name, last name, and weight (kgs or lbs). Subsequently, the console will display a healthy menu (including price) and asking you to choose which menu you’d like to order. Finally, the program will proceed to checkout order and asking you to pay some amount (the total cost will be displayed on the screen).

You can grab the sample code here.

That’s all for now, hope you like it and wait for the next part when we’ll be discussing about more advanced topics such as OOP in Python, Logging, Decorator, Generator, and some Python 3 distinctive features. Stay tuned :-)

Any comments or suggests would be well appreciated.

--

--