Published on

Python Overview

Course: Everything Data Structures and Algorithms

Authors

Introduction

Hey there 👋

Welcome to your first step into the world of data structures and algorithms — or as I like to call it, “teaching computers how to think step by step.”

To make a computer understand what we want, we use a programming language — basically, a way to talk to the computer using code. And one of the best languages to start with is Python 🐍.

Python was created by Guido van Rossum in the early 1990s. The best part? It’s completely free and super beginner-friendly. You can get it from python.org along with plenty of tutorials and examples to practice with.

When you write Python code, there’s another little program called the Python interpreter that reads your code one line at a time. It checks what you said, figures out what it means, runs it, and shows you the result. Think of it like a translator between you and your computer.

Sample Python Program

Here’s a small Python program that calculates a student’s GPA (Grade Point Average) based on the grades they enter.

print("Welcome to the GPA calculator.")
print("Please enter all your letter grades, one per line.")
print("Enter a blank line to finish.")

# mapping each letter grade to a point value
points = {
    "A+": 4.0, "A": 4.0, "A-": 3.67,
    "B+": 3.33, "B": 3.0, "B-": 2.67,
    "C+": 2.33, "C": 2.0, "C-": 1.67,
    "D+": 1.33, "D": 1.0, "F": 0.0
}

num_courses = 0
total_points = 0

while True:
    grade = input()  # get grade from user
    if grade == "":  # blank line means stop
        break
    elif grade not in points:
        print(f"Unknown grade {grade} ignored.")
    else:
        num_courses += 1
        total_points += points[grade]

if num_courses > 0:
    print(f"Your GPA is {total_points / num_courses:.3f}")

Try running this yourself — you’ll see how Python reads your grades, adds up the points, and shows your final GPA!

💡 What You Should Notice

  • Indentation (spaces) matters in Python - In Python, we don’t use curly brackets {} or keywords like end. Instead, we use spaces at the start of a line to show that certain lines belong together. So if you’re writing code inside a loop or an if-statement, make sure those lines are indented properly.
  • Comments make your code readable - Comments are like notes you leave for yourself or others. They don’t affect the program at all. Anything after a # is ignored by Python.

Objects in Python

Let’s start with something super important about Python — everything in Python is an object. That’s right! Whether it’s a number, a string, a list, or even a function — they’re all built using something called classes. You can think of a class as a blueprint, and an object as a real thing created from that blueprint.

Identifiers — Giving Things a Name

Before we can use something in Python, we usually give it a name. That’s done with an assignment statement — one of the most common things you’ll write in any Python program.

For example:

temperature = 98.6
  • On the left, we have the word temperature. This is called an identifier — basically a label or name.
  • On the right, we have the number 98.6, which is a floating-point value (a number with a decimal).

Python reads this as - “Okay, I’ll create an object that stores the value 98.6, and I’ll label it with the name temperature so we can use it later.”

A Few Rules About Identifiers

Python gives you a lot of freedom when naming things, but there are a few ground rules:

  • Names are case-sensitivetemperature and Temperature are two different things.
  • You can use letters, numbers, and underscores (_).
  • But — you can’t start a name with a number! For example, 2cool ❌ is not valid, but cool2 ✅ is fine.

Pro tip 💡: Use clear names that describe what your variable does — like age, score, or user_name. Your future self will thank you!

Now let’s talk about what these names actually point to. Python is a dynamically typed language, which simply means you don’t have to say what type a variable is when you create it.

For example :

temperature = 98.6
temperature = "Hot!"

Here, the same name temperature first pointed to a number, then later to a string — and Python is totally okay with that!

Creating and Using Objects

Alright, now that we know everything in Python is an object, let’s talk about how those objects actually come to life. In Python, when you create a new object from a class — that process is called instantiation. Think of it like this: a class is a blueprint, and when you build something using that blueprint, you’ve just instantiated it.

To create an object, we use something called a constructor — it’s like a special tool that knows how to build objects from the class.

Here’s what it looks like in Python:

temperature = float(98.6)

This line tells Python - “Hey, make me a new object of type float (a number with decimals), and give it the value 98.6.”

Pretty cool, right?

But here’s the thing — Python makes it even easier! You don’t always need to call the constructor directly. You can also use literal values, which are shortcuts to create objects instantly. So instead of writing:

temperature = float(98.6)

You can simply write:

temperature = 98.6

And Python automatically creates a float object for you behind the scenes. That number 98.6 is what we call a literal form — a simple way to make a new object.

Python’s Built-In Classes

Now that we know Python is all about objects, let’s look at the objects that come built right into the language. You don’t need to install anything or import fancy libraries — Python gives you a powerful set of built-in classes to work with from day one.

Here’s a quick overview of the most common ones:

ClassDescriptionImmutable?
boolBoolean value (True / False)
intWhole numbers (integers)
floatDecimal numbers (floating-point)
listA sequence of items that can be changed
tupleA sequence of items that cannot be changed
strA sequence of text characters
setAn unordered collection of unique elements
frozensetAn unchangeable version of a set
dictA collection of key–value pairs

What Does “Immutable” Mean?

When something is immutable, it means that once you create it, you can’t change it. You can make a new one — but the old one stays as it is.

For example:

temperature = 98.6

Here, temperature is a float. If you try to change its value later, you’re not really changing the original number — you’re just making a new one and pointing temperature to it.

That’s what we mean when we say the float class is immutable.

The bool Class

Let’s start simple — True or False, that’s all there is to it!

The bool class represents these two logical values:

is_hot = True
is_cold = False

The default constructor bool() gives you False.

A few quick rules:

  • Numbers are False if they’re zero, otherwise True.
  • Strings, lists, and other containers are False if empty, otherwise True.

Try this out:

bool(0)        # False
bool(42)       # True
bool("")       # False
bool("hi")     # True

The int Class

The int class handles whole numbers — no decimals here. You can write them just like you’d expect:

age = 25
score = -3

Python also lets you write numbers in binary, octal, or hexadecimal form:

0b1011   # binary (11 in decimal)
0o52     # octal  (42 in decimal)
0x7f     # hexadecimal (127 in decimal)

The constructor int() gives you 0 by default. But you can also use it to convert other types into integers:

int(3.14)   # 3
int(3.99)   # 3
int(-3.9)   # -3

Notice that it truncates (drops the decimal part) rather than rounding.

The float Class

If integers are for whole numbers, floats are for decimals. You’ve already seen one:

temperature = 98.6

You can also write really large or small numbers using scientific notation:

6.022e23  # means 6.022 × 10^23

And if you call float() without arguments, you’ll get:

float()  # 0.0

You can even convert other types:

float(2)  # 2.0

The list Class

A list is one of Python’s most useful tools. It’s a collection — you can store multiple items inside one variable.

Example:

colors = ["red", "green", "blue"]

Lists are mutable, meaning you can change them later:

colors.append("yellow")
print(colors)  # ['red', 'green', 'blue', 'yellow']

A few key things:

  • Lists are zero-indexed — first item is at position 0.
  • Lists are written with square brackets [ ].
  • [] means an empty list.
  • You can also create one with the constructor list().

The tuple Class

A tuple is like a list — but once you make it, you can’t change it. That’s what makes it immutable.

Tuples are written with parentheses ( ):

point = (10, 20)

And here’s a little gotcha — if you want a tuple with just one element, you must include a comma:

single = (17,)

Why? Because (17) alone would just be treated as a number in parentheses, not a tuple.

The str Class

Strings are sequences of characters, and they’re one of the most common data types you’ll use.

You can create strings using single or double quotes:

name = 'Alice'
greeting = "Hello"

You can even include quotes inside strings:

quote = "Don't worry"

If you need to include special characters, use a backslash \:

escaped = 'Don\'t worry'

And for longer text (like multi-line paragraphs), use triple quotes:

story = """Once upon a time,
there was a curious Python learner."""

The set and frozenset Classes

A set is an unordered collection of unique items — no duplicates allowed!

Example:

colors = {"red", "green", "blue"}

Sets are great when you want to quickly check if something exists:

"red" in colors  # True

You can add or remove items from a set, but remember — only immutable objects (like numbers or strings) can go inside.

There’s also a special version called frozenset, which is just a set you can’t modify.

Important note:

  • {} by itself represents an empty dictionary, not a set!
  • To make an empty set, use:
empty = set()

The dict Class

Finally, one of the most powerful types in Python — the dictionary (dict). It lets you store key–value pairs, like a real-life dictionary that maps words to meanings.

Example:

languages = {
    "ga": "Irish",
    "de": "German"
}

You can access values by their keys:

print(languages["ga"])  # Irish

Dictionaries are great for representing structured data — like users, products, or settings.

Expressions, Operators, and Precedence

Now that we’ve learned how to create and use objects, let’s take things one step further — by combining them!

In Python, you can take existing values and combine them using operators — those little symbols like +, -, *, /, and so on. Each operator tells Python to perform a specific kind of operation — adding, comparing, joining, or testing something.

The meaning of an operator depends on what kind of objects you’re working with.
For example:

a + b
  • If a and b are numbers, + means addition.
  • If a and b are strings, + means concatenation (joining them together).

Pretty cool, right? The same operator can act differently depending on the data type.

Sometimes, we want to perform multiple operations in one line. For example:

a + b * c

Here’s the catch — the order in which Python does things matters. Python follows a specific order of precedence, just like in regular math (multiplication before addition).

If you ever want to force Python to evaluate something first, just use parentheses:

(a + b) * c

Parentheses always make things clearer — and safer!

Logical Operators

Logical operators let you combine True/False conditions.

OperatorMeaningExample
notNegates a conditionnot TrueFalse
andTrue if both are trueTrue and FalseFalse
orTrue if either is trueTrue or FalseTrue

One important detail — Python uses short-circuiting for and and or. That means it stops early if it already knows the result.

Example:

if data is not None and data.is_valid():
    print("Safe to use data")

If data was None, the second part won’t even run — avoiding a crash! 🚀

Equality Operators

Python lets you compare objects in two different ways:

OperatorMeaning
isChecks if two names point to the same object
is notChecks if two names point to different objects
==Checks if two objects have the same value
!=Checks if two objects have different values

Example:

a = [1, 2]
b = [1, 2]
c = a

a == b   # True (same value)
a is b   # False (different objects)
a is c   # True (same object)

So, remember:

  • Use == when you care about value.
  • Use is when you care about identity (the same memory reference).

Comparison Operators

Comparison operators let you see how values relate to one another.

OperatorMeaning
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to

Example:

5 < 10       # True
"apple" < "banana"  # True (alphabetical order)

Strings are compared lexicographically — that means alphabetically and case-sensitively.

Arithmetic Operators

These are your math tools in Python:

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/True division (always gives a float)
//Integer division (floor division)
%Modulo (remainder)

Example:

27 / 4   # 6.75 (true division)
27 // 4  # 6 (integer division)
27 % 4   # 3 (remainder)

Python’s division is smarter than many other languages — it always makes / return a float. And it even handles negative numbers carefully:

-27 // 4   # -7
-27 % 4    # 1

Why? Because Python guarantees that - divisor * quotient + remainder = dividend

So no surprises later on.

Bitwise Operators (for integers)

These work at the bit level, useful in low-level logic or performance work.

OperatorMeaning
~Bitwise NOT
&AND
|OR
^XOR (exclusive or)
<<Shift bits left
>>Shift bits right

Example:

a = 5  # 0101
b = 3  # 0011
print(a & b)  # 1 (0001)

Sequence Operators

Strings, lists, and tuples all behave like sequences, and they support some fun and powerful operations!

OperationMeaning
s[j]Get element at index j
s[start:stop]Slice from start up to (but not including) stop
s[start:stop:step]Slice with a step interval
s + tConcatenate two sequences
k * sRepeat a sequence k times
val in sCheck if val exists in sequence
val not in sCheck if val is not in sequence

Example:

data = [10, 20, 30, 40, 50]
print(data[1:4])   # [20, 30, 40]
print(data[-1])    # 50 (last element)
print(data[:3])    # [10, 20, 30]

Because lists are mutable, you can change or delete elements:

data[0] = 99
del data[2]

Operators for Sets

Sets let you do mathematical-style operations easily!

OperatorMeaning
key in sCheck if key in set
key not in sCheck if key is not in set
s1 | s2Union (combine both)
s1 & s2Intersection (common elements)
s1 - s2Difference (only in s1)
s1 ^ s2Symmetric difference (in one but not both)
s1 <= s2Subset
s1 >= s2Superset

Example:

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)  # {1, 2, 3, 4, 5}
print(a & b)  # {3}
print(a - b)  # {1, 2}

Remember — sets are unordered, so you can’t rely on their position or use < for sorting.

Operators for Dictionaries

Dictionaries are all about key–value pairs, and Python makes working with them super intuitive.

OperationMeaning
d[key]Get value by key
d[key] = valueAdd or update a key-value pair
del d[key]Delete a key-value pair
key in dCheck if key exists
d1 == d2Compare if both dicts have same pairs

Example:

languages = {"en": "English", "de": "German"}
languages["fr"] = "French"  # Add new key-value pair
print(languages["de"])      # German
del languages["fr"]         # Remove key

Extended Assignment Operators

Python gives you shortcuts for updating values in place. Instead of writing this:

count = count + 5

You can write:

count += 5

This pattern works for most operators:

  • += (add)
  • -= (subtract)
  • *= (multiply)
  • /= (divide)
  • //= (integer divide)
  • %= (modulo)

But here’s something subtle 👇

If you’re working with mutable objects like lists, += can change the original object — while = creates a new one.

Example:

alpha = [1, 2, 3]
beta = alpha  # alias
beta += [4, 5]
print(alpha)  # [1, 2, 3, 4, 5]

beta = beta + [6, 7]
print(alpha)  # Still [1, 2, 3, 4, 5]

Why? Because += mutates the list in place, while + creates a new list and reassigns beta to it. This is one of those small but important details that makes you a Python pro! 💡