0% found this document useful (1 vote)
1K views

Introduction To Python

The document provides an introduction to the Python programming language. It discusses how Python has become the most popular programming language according to indexes like TIOBE and Stack Overflow. It is versatile, with simple syntax and applications in data, development, engineering, and education. The document then explores Python's uses, best practices, and resources for learning more about the language.

Uploaded by

HARRY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
1K views

Introduction To Python

The document provides an introduction to the Python programming language. It discusses how Python has become the most popular programming language according to indexes like TIOBE and Stack Overflow. It is versatile, with simple syntax and applications in data, development, engineering, and education. The document then explores Python's uses, best practices, and resources for learning more about the language.

Uploaded by

HARRY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

An Introduction

to Python
A Guide for Marketers, Developers,
and Data Analysts

1
An Introduction to Python
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 in 2022.

With its versatility, simple syntax and formatting,


and applications in data, development, and
education, it is becoming 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.

Source: Stack Overflow

2
An Introduction to Python
Build your optimized
website on the HubSpot CMS.
Why do the work when HubSpot can do it for you? Use HubSpt’s
CMS to build your website without being a programming expert.

HubSpot’s customizable, marketer and


developer-friendly CMS offers:

• Flexible website themes • Adaptive testing

• Built-in integrations with the • Drag-and-drop editor


HubSpot CRM and 1,000+
other tools • Serverless functions

• SEO recommendations • And more!

Get started

3
An Introduction to Python
Table of Contents
CHAPTER ONE
What is Python? 4

CHAPTER TWO
Methods & Functions 12

CHAPTER THREE
Coding Standards and Programming Best Practices 20

CHAPTER FOUR
Advanced Python 22

CHAPTER FIVE
Resources for Future Learning 24

CLOSING 26

4
An Introduction to Python
CHAPTER ONE

What is Python?
Python is one of the fastest growing, most multipurpose

Python — a free, open


programming languages available. Originally developed
in the 1990s by Dutch programmer Guido van Rossum
and expanded by community members over the years, source object-oriented
programming (OOP)
Python has gained popularity due to its collaborative nature,
powerful data capabilities, and simplicity.
language
FUN FACT

Python was named after a Monty Python sketch. According to the TIOBE Index, which ranks
programming language popularity, Python is
Source: Python Institute
the top programming language as of February
2022. So, why has Python grown as the top
choice for developers, engineers, and data
“Python works for everything. It’s a one-size- scientists, as well as an increasing number of
non-programmers?
fits-all, industry agnostic, flexible language
that allows teams to capture, enrich, and store
data, automate processes, and utilize machine
learning, among other things. Organizations
depend on Python to function.”

5
An Introduction to Python
Python is:
• Open source, with a strong community of developers
(Pythonistas and Pythoneers) and extensive library of code (PyPI)

• Object-oriented programming (OOP)

• An interpreted programming language

• Free

• Flexible

• Intuitive and simple

• Collaborative

• Trusted

• Easy to learn, reads like English

• Low cost to maintain

• Interpreted, and easier to debug than compiled languages

Python was built on the principles that code should be simple over
complex, and anyone should be able to understand it. It reads like English,
and is easier to debug than compiled languages. Because of this and
the vast capabilities that this programming language holds, Python has
become a fan favorite in the developer community.

6
An Introduction to Python
What is Python most commonly 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 “The flexibility of being able to
effects company originally founded by George Lucas), and program custom code when
Instagram are powered by Python plus Django (a Python-based
web framework).
you have large amounts of
data is invaluable. Python
Python can be used to develop websites and apps, to clean, analyze,
and model data, to build games and services, to automate processes, combines a low technical
and to create machine learning algorithms. It’s also an easy language cost of entry while providing
to learn, making it a top choice for teaching software engineering.
a near limitless set of data
Many data experts and engineers use Python when they’ve maxed
processing capabilities.”
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 Joe Camilo Ph.D.,
Engineering Director at
like MATLAB or Perl due to its ease of use, transferability between
CoVar, a machine learning
applications, and lower costs. The platform is free and upkeep is less company.
expensive and specialized than more complex tools.

Industries that Use Python


Engineering Finance Marketing Business Ecommerce Math Science + Research Education Gaming

7
An Introduction to Python
Python for Digital Marketing Setting Up and Installing Python
In digital marketing, Python is a powerful To get started using Python, download the latest version of Python to
data processing tool that picks up where your computer right from the Python website, or use a web-based code
pivot tables and business intelligence tools editor like Codepen. It’s important to have the latest version to avoid
leave off. Since it’s open source, you can bugs and have your programs run as smoothly as possible. Python is
connect any API to Python using web hooks. an interpreted language, so you write your Python code files in a text
With Python, you can create programs editor, then execute them using an interpreter.
that automate email responses, data and
Most people who use Python use an integrated development
reporting, data cleanups, and other manual
environment (IDE), which includes both the text editor and the
tasks. You can pull new trends and patterns
interpreter, displayed in a graphical user interface (GUI), like PyCharm,
from large data sets and even connect Python
VS Code, or Sublime, and these vary by industry or preferred
with your HubSpot account.
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.

Collaborative Coding in PyCharm, the Python IDE

8
An Introduction to Python
Once you’ve downloaded PyCharm or
another text editor or have Codepen open,
you’re ready to start writing Python code.
Python has their own helpful guide to getting
started that includes resources and additional
documentation based on your level of
programming experience.

To create a 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.
Creating a new Python project in PyCharm
Using a command line, here’s how to create
your Python project:

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

PyCharm, a popular Python code editor.

9
An Introduction to Python
Syntax and Format in Python
Python was designed to read like English and Once you’ve opened a Python Then, when you run the
operates using white space formatting or spaces file, basic Python syntax looks program, the output, which
or tabs that denote objects and classes. Python like this, and is entered into the appears in the terminal
programs execute from top to bottom, line by code editor: window, will be:
line, making it efficient to debug since you can
troubleshoot an issue and stop the code in the
print("Testing this code!") Testing this code!
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. Python 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.

The “Run” dropdown menu in PyCharm.

10
An Introduction to Python
PRO TIP

Using keyboard shortcuts is a game-changer in Python.

To settle the tabs versus spaces debate from


Silicon Valley… “It’s all spaces,” says Camilo.
Python Syntax + Formatting Guidelines

• Python is case sensitive

• Built-in Python functions and special keywords will


appear in color

• Some of the primary data types available in Python


are:

• Integers (whole numbers like 1, 25, or 160)


• Floats (numbers with floating points, or
decimals, like 10.16, or 8.12)
• Boolean (True or False)
Source: @FunFuse on YouTube
• Other data types include strings, lists, tuples,
dictionaries, and sets
• To define an object, you don’t need to use curly
brackets { }, instead use tabs and white space to
identify the object that a function will apply to

• Always surround text with quotes

11
An Introduction to Python
CHAPTER TWO

Methods & Functions


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. Here’s a crash course in computer science to set the
foundation for Python programming.

PYTHON GLOSSARY

TERM DEFINITION EXAMPLE

Argument The value that follows the function name, in


def test_function(fname):
parentheses. Brings information into a function.
print(fname + " Test")

Attribute A value that corresponds to a given attribute,


Object.attribute
associated using a dot/period.

Class Combines data and functionality, creates a new


class ClassName:
type of object. Methods are added to classes
<example-1>
to modify them.
.
.
.
<example-N>
12
An Introduction to Python
PYTHON GLOSSARY

TERM DEFINITION EXAMPLE

Command Line A text-based interface where you enter code.


$ python -c "print('Python Test')"
The basis for a command line interface (CLI)
Python Test
where you can execute code.

Dictionary A data type that’s a group of objects in the form of


d={
key-value pairs that map to one another, or a list of
<key>: <value>,
values associated with a matching key.
<key>: <value>,
.
.
.
<key>: <value>
}

Function A group of statements that produce a response


def test_function():
when called. They can include parameters or
print("Hello world")
return data.

List Saves multiple items as a single variable, built-


testlist = ["dog", "cat", "lizard"]
in Python function. Ordered.
print(testlist)

13
An Introduction to Python
PYTHON GLOSSARY

TERM DEFINITION EXAMPLE

Method A function applied to a class. Includes string


txt = "hello world"
methods, list methods, dictionary methods,
x = txt.capitalize()
tuple methods, set methods, and file methods.
print (x)

Module A file with a group of functions, variables, and


import testmodule
class definitions that can be imported into other
testmodule.greeting("Mario")
applications and files.

Package A directory of Python modules, must contain


import matplotlib.pyplot as plt
__init__.py file to initialize the package.
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

Script A file that contains commands that execute as a


print("Hello world")
program.

14
An Introduction to Python
PYTHON GLOSSARY

TERM DEFINITION EXAMPLE

Set A built-in data type that stores multiple items in


testset = {"dog", "cat", "lizard"}
an unordered list in a single variable, defined
print(testset)
by curly brackets { }.

String A sequence of characters, textual data.


“Hello world”
Enclosed in quotes.

Variable Temporary data storage in a computer’s


age = 20
memory. If using multiple words in a variable
name, separate them using underscores.

15
An Introduction to Python
Object-Oriented Programming Basics
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 An example of functional programming (above)
underscore before it in the code, like this: versus OOP (below) from Programming with Mosh.

_private,
Abstraction
Or, to perform name mangling, add a double underscore
before an attribute, like this: Abstraction is when you are able to block off certain
functions and methods from the rest of the code.
__private.
Abstraction is helpful in coding because it:

• Reduces the number of functions and methods needed


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

16
An Introduction to Python
Inheritance Polymorphism
Inheritance is the principle of object-oriented Polymorphism gives OOPs flexibility — rather than applying
programming that represents the streamlined, a method in the same way to each element or object,
simple nature of the language. It helps to reduce methods are applied to individual objects and can be run
redundancy by applying a set of properties and in different ways based on the type of object.
methods to multiple objects. Rather than having
This replaces more complex code called a switch-case
to repeat those properties and methods every
statement in other programming languages. In Python,
time, they can inherit the information, reducing the
you can write one line of code with a method added on to
overall amount of code.
achieve the same result.

OOPs vs Functional Programming Languages

OOPS FUNCTIONAL PROGRAMMING

• Newer programming method • Older programming method

• Related variables and functions are • Functions operate on data, variables and
combined into objects functions are separate

• Functions in OOP languages are methods • Bulkier

• Less parameters on functions, making them • Harder to debug


more flexible
• Functions depend on each other, leading to
broken code when one is changed

• Lots of parameters on functions

17
An Introduction to Python
Using Functions and Methods in Python
Functions are elements of code that produce a result and The output for the .upper method in the above
can pass parameters (data), which are noted in parentheses example is “INTRO TO PYTHON”.
following the function. An example of a function is:
The difference between methods and functions in Python
is that methods are associated with a class and dependent
def test_function(): on that class, but functions are independent. Python has a
print("Hello world") number of built-in functions, including common go-tos like
print(), range(), and list().

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 Basic Python Functions
of a method, .upper, which converts the string into all
uppercase letters, is: Arithmetic operators: Includes functions like add,
subtract, multiple, divide, percentage, and to the
power of as built-in functions.
message = 'intro to python'
print(message.upper()) 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.

18
An Introduction to Python
Leveraging 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.

Common PyPI Packages and Their Uses

NumPy
A scientific computing package that includes
mathematical functions, random number generators,
linear algebra routines, and more.

pandas “The secret to


A data manipulation package that helps with data
alignment, merging and joining data sets, aggregating
coding is knowing
data, time series-functionality, and more for academic where to look,”
and commercial purposes.

Matplotlib Emma Cotter, Ph. D.,


A 2D data visualization and plotting library for Python Environmental research
that includes plotting commands to create visualizations engineer and data expert.

like bar plots, contour plots, and more.

19
An Introduction to Python
CHAPTER THREE

Coding Standards and


Programming Best Practices
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.

Here’s what distinguishes good Python programming from bad programming, and makes a
Pythonista out of a developer. When in doubt — make it readable.

The Principles of Good Python Programming Using Black,


• Maintain consistency within modules, functions, and projects
“The Uncompromising
Code Formatter”
• Use spaces for indentation

• Avoid unnecessary whitespace When reviewing Python code for compliance,


Black, a unique Python tool, is a developer’s
• When naming files that are public on the API, describe
best friend. The Black program automatically
usage rather than implementation
formats code to comply with pycodestyle best
• Use underscores between words practices without impacting the integrity of
• Don’t use lowercase l (el), uppercase O (oh), or uppercase I the code.
(eye) as single letter variable names since they appear as 1 “I can now do refactorings in about 1% of the
and 0 in some fonts keystrokes it would have taken me previously
• Use short, lowercase names for modules with or without when we had no way for code to format itself,”
underscores says Mike Bayer, a satisfied Black user.

20
An Introduction to Python
Poor Python Formatting vs. Good Python Formatting Examples
Python code should be readable, simple, and always use 2 Keep code structure as simple as possible. While
less code when possible. Here are some examples of clunky both statements in the below example achieve the
strings and functions and how they can be simplified. same outcome, the one denoted as #pythonic is more
straightforward and considered “better” Python code.
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.

Source: Quora

3 Be explicit — concrete and specific, and speak to the


behavior of functions in the code. Below, another
developer would understand the function in the good
example.

Source: From The Hitchhiker's Guide to Python


Source: From The Hitchhiker's Guide to Python

21
An Introduction to Python
CHAPTER FOUR

Advanced Python
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.

Explore W3’s Python Tutorials for detailed practice examples and additional exercises.

Advanced Python Functions + Features

Dictionary Set
A collection of key-value pairs that A built-in Python data type that stores
match values in an associative array. multiple items in an unordered list in a testset = ["dog", "cat", "lizard"]

single variable, defined by curly brackets { }. print(testset)

Duplicates are not allowed in sets.


d={
<key>: <value>,
<key>: <value>,
<key>: <value>
List
}
A built-in Python function that saves multiple
ordered items as a single variable. When testlist = ["dog", "cat", "lizard"]

indexed, the first item is index [0], then [1], print(testlist)

and so on. Lists allow for duplicate values.

22
An Introduction to Python
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.

While Loops The Range Function


i=1
Executes a set of functions A built-in Python function that returns a sequence of
while i < 5:
or statements while a certain numbers. Ranges start at the first number, go up to
print(i)
condition remains true. (but not including) the second number, and use the
i += 1
third number as the increment. Requires integers.

x = range(4, 24, 2)
For Loops for x in x:
Executes a set of functions pets = ["dog", "cat", "lizard"] print(n
or statements for items in for x in pets:

lists, tuples, dictionaries, print(x)

sets, or strings.
Tuples
An ordered list that is unchangeable and stores
multiple items in one variable. Allows duplicate values,
List Methods and is indexed, starting with the first item as [0].
pets = ["dog", "cat", "lizard"]
Object-based functions that
pets.append("parakeet")
are applied to lists.
thistuple = ("dog", "cat", "lizard, "cat", "lizard")
print(thistuple)

23
An Introduction to Python
CHAPTER FIVE

Resources for Future Learning


To become a better developer, like becoming a better writer Virtual Code Editors
2
(and Python is the closest programming language to English, Browser-based code editors like Codepen
so it still works), you have to read and keep up with the latest provide a virtual environment to practice
best practices in the community. And write and review code Python from anywhere.
in collaboration with other programmers. Here are some
resources for continuing on your professional journey as a
developer and honing your Python skills.

1 Industry Publications
• The HubSpot Website Blog

• Science of Computer Programming Journal

• We Are Developers

• Towards Data Science Integrated Development


3
• Analytics Vidhya Environments

• Code2040 • PyCharm

• VS Code

• Sublime

• PyDev

24
An Introduction to Python
4 Frameworks 5 Developer Forums + Communities

Frameworks are platforms for developing software, No matter how long you’ve been coding, every
websites, and applications that simplify the developer will at some point or another run into
development process and help programmers something they need help with. Chances are,
speed up their processes in a standardized way. someone else has had the same issue. Rather
than wasting hours of your life attempting to
Types of frameworks include full stack frameworks,
troubleshoot solo, turn to the Python developer
micro frameworks, and asynchronous frameworks.
community and see if a Pythonista or a
Popular frameworks for Python include: Pythoneer can lend a helping hand.
Django • Python Forum
A web app framework “for perfectionists” that can be
• Stack Overflow
used for larger, more complex apps and websites.
• Reddit: r/python
Masonite
A web development app designed for software and • Reddit: r/learnpython
used for SaaS.
• Women Who Code: Python
CherryPy
• Black Girls Code
A “minimalist Python web framework” that reduces
source code size and speeds up development. • Black Tech Nation

Hug
A Python API framework that “drastically simplifies
API development over multiple interfaces,” and is
the “fastest and most modern way to create APIs
on Python3”.

25
An Introduction to Python
Closing
Power your website
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
with what it needs to
people who contribute to the community, the grow better
richer and better the language becomes.

We hope this guide helped to introduce you to The HubSpot Website Blog has all the latest
the vast capabilities that Python has to offer and tips, best practices, and inspiration for building
inspired you to automate processes, explore websites that help businesses grow.
data, and leverage the PyPI database to rethink
the way you work. Whether you’re a marketer, developer, designer, or
strategist, you need to know the most up-to-date
information about building and optimizing your website.

The HubSpot Website blog publishes helpful guides


and posts, from technical to inspirational, like:

• 10 Best GDPR-Compliant WordPress Themes

• DataOps vs. DevOps: What's the Difference?

• 12 Websites with Stunning Background Images


[+ Best Design Practices]

Subscribe to the HubSpot Website blog

26
An Introduction to Python

You might also like