{{announcement.body}}
{{announcement.title}}

My Journey With Python (Part I)

DZone 's Guide to

My Journey With Python (Part I)

An introductory tutorial on the Python language, discussing data types, looping, and other basic functions of Python.

· Web Dev Zone ·
Free Resource

I’ve been working with Java for about 14 years now, and the last two years I’ve also worked with Node.js and Golang to build some middleware AI platforms at 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, I’m gonna try here to write everything I know so far about Python. I have read different books and websites, so here I’m trying to summarize within six parts everything I gotten from these different resources. Hopefully, you'll find this article useful, especially for those of you who are trying to learn Python in a crash course.

As the title implies, this is the first part of my journey, and I’m thinking of writting my journey within as the following series:

  1. Python 3 Introduction → you are here
  2. Python 3 more Advanced Topics (coming soon)
  3. Use Django to land your first job as a web developer (coming soon)
  4. Deploy your first web app to the cloud (coming soon)
  5. Comparison between different prominent frameworks in Python (coming soon)
  6. Python for Data Enthusiasts (coming soon)

And each article will contain several sections. However, please note that the 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.

Introduction to Python 3

This section will contain the following sub-sections:

  1. What Python is and which version to 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 practices to start/manage your project.
  9. Sample Console App.

Enough with the chit-chat, let's start with the first section!

What Python Is and Which Version to Use

I won’t go into details here since you can find many articles that explain this. Shortly, I’d like to say that for those of you who are just starting to learn Python now (as I am), it's 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 a package/module manager to install/import the modules you need from the online repository. 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 modules you need is by using pip.

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 versions can cause trouble to your application, especially if you have a similar package (in different a version) used within your different applications. For instance, let's 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, it most likely will break your older (first) application since it was expected to run with version 0.11 of Flask. You get the point right? It would be ideal if you could 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 is for you to have different package versions for different applications by creating a different virtual environment for every application you have. Virtual environments also have the added benefit of being owned by the user who creates them, so they do not require an administrator's account.

There are a 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 who are still a bit confused, I captured my screen as depicted below:

How to prepare your Virtual Environment
How to prepare your Virtual Environment

There is 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 the following command from within your terminal:

pip3 install virtualenv

Which 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, 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's basic data types have are not so different from most basic data types in other programming languages. In general, you will find strings, numerals, and boolean values. Furthermore, numerals can be divided into integers (int) and floating points (float). There is also a 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 surround it by using single-quotes (’’) or double-quotes (””). Here’s an example:

hero = 'Yauri Attamimi'
msg = "Yauri isn't gonna come today"

I’d like to explain a few things here. First things 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.

The 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 themsg 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, it's important to know that Python is a dynamically typed language (in contrast to strongly-typed programming languages 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 Dynamically Typed
Python is Dynamically Typed

Other types are 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

Operators

There are several basic operators in Python. Below, I've only shown here what is mostly used within devs' daily activities.

""" Arithmetic Operators """

# Addition (a + b)
print(5 + 7)

# Subtraction (a - b)
print(19 - 8)

# Multiplication (a * b)
print(10 * 100)

# Division (a / b)
print(15 / 3)

# Modulus (a % b)
print(10 % 3)

# Exponential (a ** b)
print(5 ** 5)

# Floor Division (a // b)
print(9 // 2)
""" Comparison (Relational) Operators """

# Equal To (a == b)
print(5 == 5) 
print(9 == 5)

# Not Equal (a != b or a <> b)
print(9 != 5)
print(9 <> 5)

# Greater Than (a > b)
print(9 > 5)

# Less Than (a < b)
print(5 < 9)

# Greater Than or Equal To (a >= b)
print(9 >= 5)
print(5 >= 5)

# Less Than or Equal To (a <= b)
print(5 <= 9)
print(5 <= 5)
print(9 <= 5)
""" Assignment Operators """

# Normal Assignment (a = b)
result = 5 + 5

# Add before Assignment (a += b) 
# equal to a = a + b
result += 2 """equal to result = result + 2"""

# Subtract before Assignment (a -= b)
# equal to a = a - b
result -= 2 """equal to result = result - 2"""

# Multiply before Assignment (a *= b)
# equal to a = a * b
result *= 2 """equal to result = result * 2"""

# Divide before Assignment (a /= b)
# equal to a = a / b
result /= 2 """equal to result = result / 2"""

# Modulus before Assignment (a %= b)
# equal to a = a % b
result %= 2 """equal to result = result % 2"""

# Exponential before Assignment (a **= b)
result **= 2 """equal to result = result ** 2"""

# Floor Division Before Assignment (a //= b)
result //= 2 """equal to result = result // 2"""
""" Logical Operators """

# AND operator 
print(True and False)

# OR operator
print(True or False)

# NOT operator
print(not False)
print(not True)
""" Membership Operators """

# IN operator
list = [5, 2, 3]
print(3 in list)
print(4 in list)

# NOT IN operator
list = [7, 7, 7]
print(7 not in list)
print(9 not in list)
""" Identity Operators """

# IS operator
a = 5
b = 7
print(a is b)
str1 = "Yauri"
str2 = "Yauri"
print(str1 is str2)

# IS NOT operator
print(a is not b)
print(str1 is not str2)

Composite Data Types

Python has three 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"}
]

The difference between a list and a tuple is that a tuple is read-only (you can’t change it once you've created it), while a list is writable, and thus you can modify the list with its built-in methods. Here’s an example:

# Define and yield a new list of members 
members = ["Yauri", "Azizi", "Fadzlan"]
print(members)
# append a new member into members, then yield it
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 two types of iterations in Python 3: while loop sand forloops, 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 a value of 1, then we iterated through the while statement with the 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 xvalue at the end of the while block statement or else it will be looping forever). One important thing here, as you might have noticed already, is that in Python, instead of defining a block statement inside a curly braces { }) like in other programming languages (e.g. Java, C, etc.), Python uses indentations. 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}')

The for statement in Python differs from what you might have 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, it's a string. You can also iterate over a string or list like this:

# 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 keyworkd 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 functions. Just to recap again, a functionis a block of statements (organized code) that is reusable, and is often used to perform a single action (it better be!).

Functions provide better modularity for your application!

Here’s how to define and call 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 can see, you define a function by using the 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 to the naming convention for a “variable name,” i.e. all written in lowercase and separated with an underscore (_) if it has more than one word.

Exceptions

An exception is a way to catch any error thrown from your program. Your program might be syntactically correct, but sometimes errors 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 time, the program will unexpectedly fail 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 = 2 / a
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 Operations in Python

There are many IO operations in Python, yet I will merely discuss the input operation in the context of getting an input from the console and printing an output to the console, since this is what we need for our last section when we discuss our console 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 is that every input will be treated as a string by default, hence if you’d like to deal 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):

Defining a package in Python

As depicted in the above image, we also created a file, converter.py, inside our new utils package. Here’s the sourcecode:

def lbs_to_kg(weight):
  return 0.45 * lbs

def kg_to_lbs(weight):
  return weight / 0.45

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 Practices to Start/Manage Your Project

There are several best practices to maintain your project. First and foremost, as discussed previously in section 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 the virtualenvcommand to create the virtual environment from within your project folder. And since Python 3, there has been a built-in virtual environment included. Thus, instead of using the virtualenvcommand as shown above, you can also use the 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.

Activating Python virtual environment
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 the changes made to your terminal session are temporary and private to that session, so it won’t persist when you close the terminal.

After creating 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 list all of your dependency libraries (including the version) within the requirements.txt file. Consider this file the same as a package.json (in Node.js) 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 (venvin our case) into our .gitignore file (if you’re using Git).

That’s all of the best practices I have found useful, at least for now!

Sample Console App

For our basic sample app, we’ll be creating a simple console application that asks a user to enter some basic information, such as their first name, last name, and weight (kgs or lbs). Subsequently, the console will display a healthy menu (including price) and ask you to choose which menu you’d like to order. Finally, the program will proceed to checkout and ask 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 more advanced topics such as OOP in Python, Logging, Decorators, Generators, and some Python 3 distinctive features. Stay tuned!

Any comments or suggestions would be well appreciated.
Topics:
python ,python 3 ,web dev ,python tutorial for beginners ,pip

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}