Python Fundamentals: Variables, Data Types, Operators, and more

Python
⌛ 8 minutes read

Introduction

Hello developers! You’re about to dive into the fascinating world of Python—a favorite among data enthusiasts due to its readability and versatility. This beginner’s python fundamentals guide will equip you with Python essentials. We’ll simplify complex terms like variables, data types, operators, and control structures, and explore them step-by-step in a friendly, accessible way.

By the end, you’ll understand these fundamentals and know how to apply them in real-world scenarios. Ready to venture into Python and data analysis? Get comfortable and let’s begin!

Python Variables

Variables are our way of storing information in Python, and we can access or change that information whenever we want—hence the name ‘variable‘.

So, how do we create variables in Python? Let’s say you want to store the number 5 in a variable. Here’s how you do it:

x = 5

In this case, x is the variable name, = is the assignment operator (think of it as the word “is“), and 5 is the value. So, in plain English, we’re saying “x is 5“. From now on, whenever we refer to x in our code, Python will understand it as 5.

But x isn’t a very descriptive name, is it? In Python, we can name our variables almost anything we want. However, there are some rules:

  1. Variable names must start with a letter or underscore ( _ ) but not a number. So _myVariable or myVariable are valid names, while 1myVariable isn’t.
  2. They can contain letters (upper or lower case), numbers, or underscores. But no spaces or special characters!
  3. They should be descriptive. For instance, if you’re storing age, use age instead of a generic name like x.

Here’s a better variable example:

age = 25

In this case, age is the variable, and it holds the value of 25.

Now, let’s dive a bit deeper. Python variables can be mutable or immutable.

Mutable Variables

Think of mutable variables like a whiteboard in a classroom. You can write on it, erase what you’ve written, and write something else entirely—all on the same whiteboard. The information (or value) can change, but it’s still the same whiteboard (or variable). In Python, mutable means that the content of the variable can change.

Imagine you have a list of your favorite fruits:

favorite_fruits = ["apple", "banana", "grape"]

You can easily swap grape for strawberry without creating a whole new list:

favorite_fruits[2] = "strawberry"  # Now the list is ["apple", "banana", "strawberry"]

You’ve changed the contents, but it’s still the same favorite_fruits variable. That’s what we mean by mutable.

Immutable Variables

On the other hand, think of immutable variables as a page in a printed book. Once it’s printed, you can’t change the words on the page. If you want to “change” something, you’d have to print a whole new page. In Python, immutable means that the content of the variable can’t change.

For instance, if you have a string:

my_string = "hello"

You can’t change the first letter h to j to make “jello“. If you try my_string[0] = "j", Python will give you an error. You’d have to create a whole new string, like my_string2 = "jello".

So in essence, mutable variables are like whiteboards—they can be changed. Immutable variables are like printed pages—they can’t be changed without creating a new variable.

Note: Don’t worry if you didn’t get the mutable and immutable, we will dive into the datatypes in detail in the next section

Python Data Types

If variables are the containers that hold our data, data types define the “type” of content that these containers can hold.

Imagine you’re organizing a huge party. You have different containers to store various party items. You wouldn’t put the balloons in the refrigerator, would you? Or the ice cream in the wardrobe? Just as we use different containers for different items in real life, we use different data types for different kinds of data in Python.

Now, let’s dive into the different data types Python has to offer.

Primary Data Types

Primary data types are the building blocks of data manipulation in Python. Think of them as the atom in the world of data—they’re the smallest and simplest forms of data. Here are the primary data types:

Integer (int)

These are whole numbers, without a decimal point, like 5 or -12. Integers are immutable, meaning you can’t change a part of them without creating a new integer.

x = 10

Float (float)

These are decimal numbers. Like integers, they’re also immutable.

y = 3.14

String (str)

Strings are sequences of characters enclosed in quotes ('' or “”). They can contain letters, numbers, or symbols. Strings are also immutable.

greeting = "Hello, Python explorers!"

Boolean (bool)

Booleans represent one of two values: True or False. They’re quite handy when you want to check a condition—like whether it’s raining outside or not. Booleans, like integers, floats, and strings, are also immutable.

is_raining = False

Composite Data Types

While primary data types are the foundation, Python also offers composite data types for more complex operations. These data types can hold multiple pieces of data. Let’s take a look:

List (list)

A list is an ordered collection of items, which can be of different data types. The items are enclosed in square brackets [] and separated by commas. Lists are mutable—you can add, remove, or change items after the list is created.

my_list = [1, 2.5, "apple", True]

Tuple (tuple)

A tuple is similar to a list, but it’s enclosed in parentheses () instead of brackets. The key difference is that tuples are immutable—once a tuple is created, you can’t change it.

my_tuple = (1, 2.5, "apple", True)

Set (set)

A set is an unordered collection of unique items. Sets are enclosed in curly brackets {}, but since they’re unordered, sets don’t support indexing. Sets are mutable—you can add or remove items after it’s created.

my_set = {1, 2.5, "apple", True}

Dictionary (dict)

A dictionary is an unordered collection of key-value pairs. It’s like a real-life dictionary, where you look up a word (the key) and get its definition (the value). Dictionaries are mutable—you can add, remove, or change items after it’s created.

my_dict = {"name": "John", "age": 30}

Python Operators

Alright, it’s time to step into the world of Python operators. As the name suggests, operators in Python help us to perform various operations on our data, such as arithmetic calculations, comparisons, assignments, and much more. Let’s dive in!

Arithmetic Operators

First up, we have the arithmetic operators. These are the basic tools for doing math in Python:

Addition (+)

This operator adds two values together.

x = 5 + 3  # x is now 8

Subtraction (-)

This operator subtracts the second value from the first.

y = 10 - 2  # y is now 8

Multiplication (*)

This operator multiplies two values.

z = 4 * 2  # z is now 8

Division (/)

This operator divides the first value by the second.

w = 16 / 2  # w is now 8.0 (Note: division always results in a float!)

There are a few other arithmetic operators in Python, like the modulus operator (%), floor division (//), and exponentiation (**). But don’t worry about them for now. We’re focusing on the basics!

Comparison Operators

Next, we have comparison operators. They compare two values and give us a Boolean result—either True or False. These operators are essential when making decisions in our code. Here are the most common ones:

Equal to (==)

This operator checks if two values are equal.

(5 == 5)  # Returns True

Not equal to (!=)

This operator checks if two values are not equal.

(5 != 3)  # Returns True

Greater than (>) and less than (<)

These operators check if one value is greater than or less than another.

(5 > 3)  # Returns True
(5 < 3)  # Returns False

There are also the greater than or equal to (>=) and less than or equal to (<=) operators.

Assignment Operators

Lastly, we have assignment operators. These are used to assign values to variables. We’ve already met the simple assignment operator (=), but there are several others that perform an operation and an assignment in one go:

Add and assign (+=)

This operator adds the right value to the left variable and then assigns the result back to the left variable.

x = 5
x += 3  # Equivalent to x = x + 3; x is now 8

Subtract and assign (-=)

This operator works similarly but with subtraction.

y = 10
y -= 2  # Equivalent to y = y - 2; y is now 8

Again, there are more assignment operators in Python, like *=, /=, and so on, but these two should give you a good start.

Python Control Structures

Python control structures are like the traffic signals of our code, guiding data flow, controlling the order of execution, and giving us the power to make decisions. Let’s get going!

If, Elif, and Else

At some point, we need our program to make choices. This is where if, elif, and else come in:

If

This is the most basic form of control. The if statement checks if a condition is true. If it is, it executes a block of code.

temperature = 30

if temperature > 25:
    print("It's a hot day!")

In this example, the message “It’s a hot day!” will only be printed if the temperature is above 25.

Elif

Short for ‘else if‘, elif allows us to check additional conditions if the previous conditions were false.

temperature = 20

if temperature > 25:
    print("It's a hot day!")
elif temperature > 15:
    print("It's a warm day!")

Here, if the temperature is not above 25 but is above 15, the message “It’s a warm day!” will be printed.

Else

else acts as the final catch-all if all previous conditions have been false.

temperature = 10

if temperature > 25:
    print("It's a hot day!")
elif temperature > 15:
    print("It's a warm day!")
else:
    print("It's a cold day!")

In this case, the temperature is neither above 25 nor above 15, so the message “It’s a cold day!” is printed.

Loops

Now let’s discuss loops, which allow us to repeat a block of code multiple times. Python has two types of loops:

For Loop

A for loop iterates over a sequence, such as a list or a string, and executes a block of code for each item.

for i in range(5):
    print(i)

This loop will print the numbers 0 to 4.

While Loop

A while loop repeats a block of code as long as a specific condition is true.

counter = 0

while counter < 5:
    print(counter)
    counter += 1

This loop will also print the numbers 0 to 4.

Python Functions

If you’ve ever found yourself typing the same set of instructions more than once, functions are your new best friends. Let’s dive in!

Think of a function as a machine in a factory. You feed it some raw materials (these are your inputs or arguments), it does some work, and then it gives you a finished product (this is your return value). Just like factory machines, functions help us automate repetitive tasks.

def greet(name):
    return f"Hello, {name}!"

In the above example, greet is a function that takes one argument, name, and returns a greeting string. We can use this function as many times as we want:

print(greet("Alice"))  # Prints: Hello, Alice!
print(greet("Bob"))    # Prints: Hello, Bob!

A function in Python has a few key parts:

  • def Keyword: This is how Python knows you’re defining a function.
  • Function Name: This is the name you’ll use to call your function. Just like variable names, it should be descriptive.
  • Parameters: These are the inputs your function needs to do its job. You can have as many parameters as you need or none at all.
  • Colon (:): This is how Python knows where the body of your function starts.
  • Body: This is where your function does its work. Everything in the body is indented to the right.
  • return Statement: This is how your function gives back a result. Once Python hits the return statement, the function is over and the returned value is given back. If you don’t include a return statement, Python will return None by default.

Functions are one of the most powerful tools in a programmer’s toolbox for a few reasons:

  • Reusability: If you find yourself writing the same code multiple times, a function can save you time and effort.
  • Abstraction: Functions allow you to hide complex code and make your programs easier to read and maintain.
  • Modularity: Functions break your program into smaller, more manageable pieces

Let’s create a function that takes multiple parameters:

def calculate_rectangle_area(length, width):
    return length * width

print(calculate_rectangle_area(5, 10))  # Prints the area of a rectangle with length 5 and width 10

In this example, calculate_rectangle_area function takes two parameters, length and width, and returns the area of a rectangle using the formula length * width.

Further Reading

Conclusion

In conclusion, we’ve navigated the fundamentals of Python, mastering everything from variables to functions. Each of these elements is a vital tool in your coding arsenal, helping you write cleaner, more efficient code.

But remember, understanding is only the first step—practice is the real game-changer. So, dive in, write code, make mistakes, and above all, enjoy the process. That’s how we grow as coders. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *