Free Guide

Introduction to Python

Discover how Python's versatility and simplicity make it the ideal language for automating processes, analyzing data, and building applications across industries.

Easily generate your business website with HubSpot's free AI website builder. No coding required.

Introduction

Python has quickly become the most-searched programming language on Stack Overflow and the #1 language on the TIOBE index, surpassing C and Java.

Developed in the 1990s by Dutch programmer Guido van Rossum (who a named it after a Month Python sketch), Python was continuously expanded by community members and ultimately gained wide popularity due to its collaborative nature, powerful data capabilities, and simplicity.

Today, Python is one of the fastest growing, most multipurpose programming languages available. But, why?

Compared to other programming languages, Python has many pros, including:

  • Object-oriented programming (OOP)
  • An interpreted programming language
  • Free to access and low-cost to maintain
  • Flexible
  • Intuitive and simple
  • Collaborative
  • Trusted
  • Easy to learn as it reads like English
  • Easier to debug than compiled languages

With its versatility, simple syntax and formatting, and applications in data, development, and education, it's become the preferred programming language of data experts, engineers, and operations professionals in all industries.

This guide will explore Python programming, uses, and best practices, and provide resources to help you leverage Python in your day-to-day role. Let's get started.

Chapter 1

Python Fundamentals

Python is an open source programming language, with a strong community of developers (Pythonistas and Pythoneers) and extensive library of code (PyPI). But what exactly does it do - and why is it so popular?

 

What is Python?

Python is a one-size-fits-all, industry agnostic, flexible language that businesses have learned to depend on to collect, leverage, and store data. It also enables teams to automate processes and utilize machine learning, among other things.

What Data Types are Compatible With Python?

Numbers and figures likely come to mind when you hear “data.” But it’s so much more than that. Text snippets, images, and videos are also classified as data.

Python gives users options around the type of data they can collect.

For example, you can run a text or sentiment analysis on social media comments to gain insight into your customers’ thoughts and feelings regarding your product or service. In other words, you can count it as data if it’s trackable.

Numbers, like dollars earned or lost, are essential to understanding how well your business is doing. However, metrics like customer satisfaction are also valuable to help you understand what your business is doing right and how you can improve.

AI Website Generator for Business Websites

Answer a few prompts and watch your website come to life.
No coding required.

What is Python Used For?

Python is mainly used for data science, data visualization, machine learning, and website and app development. Top platforms like YouTube, Pinterest, Google, Industrial Light and Magic (special effects company originally founded by George Lucas), and Instagram are powered by Python plus Django (a Python-based web framework).

Python can be used to develop websites and apps, to clean, analyze, and model data, to build games and services, to automate processes, and to create machine learning algorithms. It's also an easy language to learn, making it a top choice for teaching software engineering.

Many data experts and engineers use Python when they've maxed out the functionality of Excel or Google Sheets' pivot tables, or it's simply too much data for those programs to execute.

Python has proven a more adaptable solution than industry-specific competitors like MATLAB or Perl due to its ease of use, transferability between applications, and lower costs. The platform is free and upkeep is less expensive and specialized than more complex tools.

Joe Camilo headshot in front of mountains

The flexibility of being able toprogram custom code whenyou have large amounts ofdata is invaluable. Pythoncombines a low technicalcost of entry while providinga near limitless set of dataprocessing capabilities.

Joe Camilo, Ph. D.

Engineering Director

Covar

Industries That Use Python

  • Engineering
  • Finance
  • Marketing
  • Business
  • Ecommerce
  • Mathematics
  • Science
  • Research
  • Education
  • Gaming

Python in Digital Marketing

In digital marketing, Python is a powerful data processing tool that picks up where pivot tables and business intelligence tools leave off. Since it's open source, you can connect any API to Python using web hooks.

With Python, you can create programs that automate email responses, data and reporting, data cleanups, and other manual tasks.

You can pull new trends and patterns from large data sets and even connect Python with your HubSpot account.

Chapter 2

Setting Up & Installing Python

Python was created to be uncomplicated., streamlined, and easy to use. It's installation process is no different.

Starting a new programming language doesn't have to be intimidating. Here's an easy, step-by-step explanation of how to get started.
HS_Pictograms_Web Search

Step 1

Download Python.

Download the latest version of Python to your computer right from the official Python website, or use a web-based code editor like Codepen.

It's important to have the latest version to avoid bugs and have your programs run as smoothly as possible. Python is an interpreted language, so you write your Python code files in a text editor, then execute them using an interpreter..

HS_Pictograms_AI_writer

Step 2

Pick an IDE.

.Most Python users leverage an integrated development environment (IDE), which includes both the text editor and the interpreter, displayed in a graphical user interface (GUI), like PyCharm, VS Code, or Sublime, and these vary by industry or preferred programming language. Most are free and they include features like checking code for errors, color coding, customizable UI, plugins, improved code quality, and other collaboration and developer tools.

Once you've downloaded PyCharm, another text editor, or Codepen open, you're ready to start writing Python code.

HS_Pictograms_Solutions_500px

Step 3

Create your first Python program.

Name your Python file using the command line. Your IDE will prompt the file storage location and create a new virtual environment when you go to create a new project file, saving with the extension .py. Using a command line, here's how to create your Python project:

C:\Users\Your Name>python newproject.py

HS_Pictograms_Resources-Library

Step 4

Leverage Python learning resources

Python has its own helpful guide to getting started that includes resources and additional documentation based on your level of programming experience.

Looking for more education? Keep reading this guide, or click here for more Python resources.

Syntax & Formatting Python

Python was designed to read like English and operates using white space formatting or spaces or tabs that denote objects and classes. Python programs execute from top to bottom, line by line, making it efficient to debug since you can troubleshoot an issue and stop the code in the middle, rather than having to stop the entire program like in a compiled language like C++.

To write in Python, use the code editor in the top screen to write your code.

Screenshot 2025-08-21 at 10.29.43 PMPython code includes declaring variables, creating lists, processing user inputted data, and using functions to manipulate data. This can be coded manually, or implemented using imported packages that others developed. When you are ready to run your code, use the "Run" function and the output will appear in the terminal window below.

If there are any errors, Python will identify the error using the line where the error has occurred and provide insights as to why the error is happening.

Once you've opened a Python file, basic Python syntax looks like this, and is entered into the code editor:

print("Testing this code!")

Then, when you run the program, the output, which appears in the terminal window, will be:

Testing this code!

Chapter 3

Methods & Functions

Here's a crash course in computer science to set the foundation for Python programming. Get started by clicking through the terms and examples in the Python Glossary below.

Definition

The value that follows the function name, in parentheses. Brings information into a function.

Example

def test_function(fname):<br>print(fname + " Test")

Definition

A value that corresponds to a given attribute, associated using a dot/period.

Example

Object.attribute

Definition

Combines data and functionality, creates a new type of object. Methods are added to classes to modify them.

Example

class ClassName:<br><example-1><br>.<br>.<br>.<br><example-N>

Definition

A text-based interface where you enter code. The basis for a command line interface (CLI) where you can execute code.

Example

$ python -c "print('Python Test')"<br>Python Test

Definition

A group of statements that produce a response when called. They can include parameters or return data.

Example

def test_function():<br>print("Hello world")

Definition

Saves multiple items as a single variable, built-in Python function. Ordered.

Example

testlist = ["dog", "cat", "lizard"]<br>print(testlist)

Definition

A data type that's a group of objects in the form of key-value pairs that map to one another, or a list of values associated with a matching key.

Example

d = {<br><key>: <value>,<br><key>: <value>,<br>.<br>.<br>.<br><key>: <value><br>}

Definition

A function applied to a class. Includes string methods, list methods, dictionary methods, tuple methods, set methods, and file methods.

Example

txt = "hello world"<br>x = txt.capitalize()<br>print (x)

Definition

A file with a group of functions, variables, and class definitions that can be imported into other applications and files.

Example

import testmodule<br>testmodule.greeting("Mario")

Definition

A directory of Python modules, must contain init.py file to initialize the package.

Example

import matplotlib.pyplot as plt<br>plt.plot([1,2,3,4])<br>plt.ylabel('some numbers')<br>plt.show()

Definition

A file that contains commands that execute as a program.

Example

print("Hello world")

Definition

A built-in data type that stores multiple items in an unordered list in a single variable, defined by curly brackets { }.

Example

testset = {"dog", "cat", "lizard"}<br>print(testset)

Definition

A sequence of characters, textual data. Enclosed in quotes.

Example

"Hello world"

Definition

Temporary data storage in a computer's memory. If using multiple words in a variable name, separate them using underscores.

Example

age = 20

Object-Oriented Programming Basics

Python is an object-oriented programming (OOP) language, meaning the focus of the code is on the objects or datasets, rather than on the functions themselves.

The four main elements of OOPs are encapsulation, abstraction, inheritance, and polymorphism. Object-oriented programming was designed to simplify the code development process, minimizing the need to copy and paste code.

Encapsulation

Encapsulation is when a group of similar variables and functions are combined into one object, by defining them in a group like a class. Encapsulation helps protect and secure data and prevents code from being altered by others. To make a given element private in Python, add an underscore before it in the code, like this:

_private,

Or, to perform name mangling, add a double underscore before an attribute, like this:

__private.

Encapsulation makes code more efficient by eliminating the need for lengthy parameters attached to functions. And it allows you to reuse objects in different places and programs.

Abstraction

Abstraction is when you are able to block off certain functions and methods from the rest of the code. Abstraction is helpful in coding because it:

  • Reduces the number of functions and methods needed
  • Simplifies the code • Minimizes the effects of changes
Inheritance

Inheritance is the principle of object-oriented programming that represents the streamlined, simple nature of the language. It helps to reduce redundancy by applying a set of properties and methods to multiple objects. Rather than having to repeat those properties and methods every time, they can inherit the information, reducing the overall amount of code.

Polymorphism

Polymorphism gives OOPs flexibility — rather than applying a method in the same way to each element or object, methods are applied to individual objects and can be run in different ways based on the type of object.

This replaces more complex code called a switch-case statement in other programming languages. In Python, you can write one line of code with a method added on to achieve the same result.

Click below to reveal the pros and cons of OOPS versus Functional Programming.

  • Newer programming method
  • Related variables and functions are combined into objects
  • Functions in OOP languages are methods
  • Less parameters on functions, making them more flexible

  • Older programming method
  • Functions operate on data, variables and functions are separate
  • Bulkier
  • Harder to debug
  • Functions depend on each other, leading to broken code when one is changed
  • Lots of parameters on functions

Using Functions and Methods in Python

Functions are elements of code that produce a result and can pass parameters (data), which are noted in parentheses following the function. An example of a function is:

def test_function():

    print("Hello world")

A method is a modification applied to an object that can operate or return data within a given class. In other words, it's a function applied to an object. An example of a method, .upper, which converts the string into all uppercase letters, is:

message = 'intro to python'

print(message.upper())

The output for the .upper method in the above example is "INTRO TO PYTHON".

The difference between methods and functions in Python is that methods are associated with a class and dependent on that class, but functions are independent. Python has a number of built-in functions, including common go-tos like print(), range(), and list().

Basic Python Functions

  • Arithmetic operators: Includes functions like add, subtract, multiple, divide, percentage, and to the power of as built-in functions.
  • Comparison operators: Greater than or equal to, greater than, less than or equal to, less than, equal to, not equal to.
  • Logical operators: And, or, and not. Combines arithmetic and comparison operators into logical statements.
  • If statements: If, then statements.

PyPI: The Python Package Index

PyPI is the centralized database of Python packages maintained by the community — it's a place to upload or access packages for different use cases, industries, and data needs. With more than 350,000 projects, you're bound to find something that helps with your next project.

"The secret to coding is knowing where to look,"
Emma Cotter, Ph. D.,
Environmental research engineer and data expert.

Common PyPI Packages and Their Uses
  • NumPy: A scientific computing package that includes mathematical functions, random number generators, linear algebra routines, and more.
  • pandas: A data manipulation package that helps with data alignment, merging and joining data sets, aggregating data, time series-functionality, and more for academic and commercial purposes.
  • Matplotlib: A 2D data visualization and plotting library for Python that includes plotting commands to create visualizations like bar plots, contour plots, and more.

 

Chapter 4

Coding & Programming Best Practices

Here's what distinguishes good Python programming from bad programming, and makes a Pythonista out of a developer. 

 

When in doubt — make it readable.

Good quality Python code should follow PEP 8, the most up-to-date style guide for Python that's based on Guido van Rossum's original style guide and tenets of the language.

 

Using Black: The Uncompromising Code Formatter

When reviewing Python code for compliance, Black, a unique Python tool, is a developer's best friend. The Black program automatically formats code to comply with pycodestyle best practices without impacting the integrity of the code.

"I can now do refactorings in about 1% of the keystrokes it would have taken me previously when we had no way for code to format itself."
Mike Bayer
, a satisfied Black user.

Bad Python vs. Good Python Formatting Examples

Python code should be readable, simple, and always use less code when possible. Here are some examples of clunky strings and functions and how they can be simplified.

1. Only use one statement per line.

Don't combine disjointed statements, like if <complex comparison> and <other complex comparison> in the example below, on the same line.

print('one'); print('two')

if x == 1: print('one')

if <complex comparison> and <other complex comparison>:
    # do something

print('one')
print('two')

if x == 1:
    print('one')

cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
    # do something

def make_complex(*args):
    x, y = args
    return dict(**locals())

def make_complex(x, y):
    return {'x': x, 'y': y}

Chapter 5

Advanced Python Functions and Features

Python enables developers to connect complex data sets, to automate processes, and to visualize data.

Here are more Python elements and functions that enable more advanced programs.

A collection of key-value pairs that match values in an associative array.

d = {

    <key>: <value>,

    <key>: <value>,

    <key>: <value>

}

A built-in Python data type that stores multiple items in an unordered list in a single variable, defined by curly brackets { }. Duplicates are not allowed in sets.

testset = ["dog", "cat", "lizard"]

print(testset)

A built-in Python function that saves multiple ordered items as a single variable. When indexed, the first item is index [0], then [1], and so on. Lists allow for duplicate values.

testlist = ["dog", "cat", "lizard"]

print(testlist)

Command Line + Command Line Arguments

The command line is where you invoke Python and can add options like -c (command), -m (module-name), scripts, and arguments. The interpreter reads the command line within the environment to learn which settings to use. Command-line arguments are additional information within the line of a program after the program.py on the command line.

Executes a set of functions or statements while a certain condition remains true.

i = 1

while i < 5:

    print(i)

    i += 1

For Loops
Executes a set of functions or statements for items in lists, tuples, dictionaries, sets, or strings.

pets = ["dog", "cat", "lizard"]

for x in pets:

    print(x)

List Methods
Object-based functions that are applied to lists.

pets = ["dog", "cat", "lizard"]

pets.append("parakeet")

The Range Function
A built-in Python function that returns a sequence of numbers. Ranges start at the first number, go up to (but not including) the second number, and use the third number as the increment. Requires integers.

x = range(4, 24, 2)

for x in x:

    print(n)

Tuples
An ordered list that is unchangeable and stores multiple items in one variable. Allows duplicate values, and is indexed, starting with the first item as [0].

thistuple = ("dog", "cat", "lizard", "cat", "lizard")

print(thistuple)

Executes a set of functions or statements for items in lists, tuples, dictionaries, sets, or strings.

pets = ["dog", "cat", "lizard"]

for x in pets:

    print(x)

Object-based functions that are applied to lists.

pets = ["dog", "cat", "lizard"]

pets.append("parakeet")

The Range Function
A built-in Python function that returns a sequence of numbers. Ranges start at the first number, go up to (but not including) the second number, and use the third number as the increment. Requires integers.

x = range(4, 24, 2)

for x in x:

    print(n)

An ordered list that is unchangeable and stores multiple items in one variable. Allows duplicate values, and is indexed, starting with the first item as [0].

thistuple = ("dog", "cat", "lizard", "cat", "lizard")

print(thistuple)

Resources for Future Learning

To become a better developer, like becoming a better writer (and Python is the closest programming language to English, so it still works), you have to read and keep up with the latest best practices in the community. And write and review code in collaboration with other programmers. Here are some resources for continuing on your professional journey as a developer and honing your Python skills.

Powering Python to Supercharge Growth

Python has quickly become one of the most popular, versatile programming languages used by developers. And just as Guido van Rossum imagined when he first developed it, the more people who contribute to the community, the richer and better the language becomes.

We hope this guide helped to introduce you to the vast capabilities that Python has to offer and inspired you to automate processes, explore data, and leverage the PyPI database to rethink the way you work.

Generate Your Business Site with AI

Just answer a few easy prompts and watch your website come to life. No coding required.