Python for Data Engineers & Data Analysts – Day 2: Mastering Variables, Data Types, and Operators

Telegram Group Join Now
WhatsApp Group Join Now

Welcome back to our 30-day Python series. I’m thrilled to have you join me again as we dive into Day 2 of this exciting journey. After setting up our Python environment in Day 1, we’re ready to explore some foundational concepts that will power our coding adventures. Today, we’ll cover variablesdata typestype castingoperators, and assignment operators. To bring it all together, we’ll tackle two fun mini projects and wrap up with a set of coding exercises to sharpen our skills.

Here’s what we’ll explore in this blog post:

  • Variables: How I store and manage data in Python
  • Data Types: Understanding strings, integers, floats, and booleans
  • Type Casting: Converting data types to fit my needs
  • Operators: Using arithmetic, comparison, and logical tools
  • Assignment Operators: Updating variables with efficiency
  • Mini Projects: Building a calculator and an e-commerce cart
  • Coding Exercises: 10 tasks to practice what we’ve learned

Let’s jump in and start coding.


Variables: Storing Data in Python

When I began learning Python, I quickly realized that variables are like the storage boxes of programming—they let me hold onto data and use it whenever I need. In Python, creating a variable is incredibly simple: I just pick a name and assign it a value using the equals sign (=).

For example:

name = "Alice"
age = 25
price = 19.99
is_learning = True

In this snippet:

  • name holds the string "Alice".
  • age stores the integer 25.
  • price contains the float 19.99.
  • is_learning is a boolean set to True.

One thing I love about Python is its flexibility with strings—I can use either single quotes (') or double quotes ("). Both work the same way:

food = 'Pizza'
restaurant = "Pizza Hut"

Whether I choose 'Pizza' or "Pizza", Python doesn’t mind, which makes writing code feel a bit more personal.

Why Variables Matter

Variables are more than just placeholders—they make my code readable and adaptable. Imagine I’m writing a program to track sales. Instead of typing 19.99 every time I need the price of an item, I can store it in a variable like price and reuse it. If the price changes, I only update it once. That’s efficiency!

Naming Tips

I’ve learned a few rules to keep my variable names meaningful:

  • Be descriptivetotal_cost beats tc.
  • Start with a letter or underscoreprice or _price works, but 1price doesn’t.
  • No spaces: Use underscores instead, like user_name.
  • Case sensitivityPrice and price are different variables in Python.

With variables in my toolkit, I’m ready to store all kinds of data. Let’s see what types of data I can work with next.


Data Types: The Building Blocks of Data

Every piece of data in Python has a type, and understanding these types is key to knowing what I can do with my variables. Today, we’re focusing on four main data types: stringsintegersfloats, and booleans.

Exploring the Four Data Types

  • Strings (str): These are for text—think names, messages, or anything I want to write. I wrap them in quotes.
    Example: "Hello, Python!" or 'Day 2'
  • Integers (int): Whole numbers, no decimals, perfect for counting.
    Example: 100-7
  • Floats (float): Numbers with decimal points, great for measurements or calculations.
    Example: 3.140.99
  • Booleans (bool): Just two values—True or False. I use these for decisions.
    Example: TrueFalse

To check a variable’s type, I use the type() function. Here’s how it works:

print(type(name))       # Output: <class 'str'>
print(type(age))        # Output: <class 'int'>
print(type(price))      # Output: <class 'float'>
print(type(is_learning))# Output: <class 'bool'>

Why Data Types Are Crucial

At first, I wondered why I needed to care about data types. Then I tried adding two pieces of data:

print(5 + 3)      # Output: 8
print("5" + "3")  # Output: "53"

When I add integers, I get a sum. But with strings, Python concatenates them—sticks them together! Data types dictate how operations behave, so knowing them helps me avoid surprises.

For example, if I’m calculating a total cost, I need numbers (int or float), not strings. This distinction becomes even clearer when I start working with user input, which we’ll tackle soon.


Type Casting: Converting Between Data Types

Sometimes, the data I get isn’t in the form I need. That’s where type casting comes in—it’s like a magic wand that transforms one data type into another. Python gives me these handy functions:

  • str(): Turns anything into a string
  • int(): Converts to an integer
  • float(): Makes a float
  • bool(): Creates a boolean

A Real-World Example

The input() function is a big reason I use type casting. It always returns a string, even if I type a number. Check this out:

age = input("How old are you? ")  # I type "25", but age is "25" (a string)
age = int(age)                    # Now age is 25 (an integer)

Without that int(), I couldn’t do math with age—Python would treat it as text.

More Casting Examples

Here’s how I can play with types:

  • String to Integerint("42") → 42
  • Integer to Stringstr(42) → "42"
  • String to Floatfloat("9.99") → 9.99
  • Anything to Booleanbool("") → Falsebool("hi") → True

Booleans are interesting—empty strings or zero become False, while almost anything else becomes True.

Watch Out for Errors

I’ve hit a few bumps with type casting. For instance:

int("hello")  # Error: ValueError: invalid literal for int()

Python can’t turn "hello" into a number—it doesn’t make sense. Same with decimals to integers:

int("3.14")   # Error: ValueError

If I need an integer from "3.14", I first cast it to a float, then to an integer: int(float("3.14")) → 3.

Type casting is a skill I’ll use a lot, especially in our mini projects. Let’s move on to operators next!


Operators: Performing Operations in Python

Operators are the tools I use to manipulate my data—think of them as the verbs of programming. Today, we’re covering three types: arithmeticcomparison, and logical operators.

Arithmetic Operators

These are my go-to for math:

  • + : Addition
    Example: 10 + 5 → 15
  • - : Subtraction
    Example: 10 - 5 → 5
  • * : Multiplication
    Example: 10 * 5 → 50
  • / : Division (gives a float)
    Example: 10 / 4 → 2.5
  • % : Modulus (remainder)
    Example: 10 % 3 → 1
  • // : Floor Division (rounds down)
    Example: 10 // 4 → 2
  • ** : Exponentiation (power)
    Example: 2 ** 3 → 8

I love how // and % work together—division and remainder in one go. For instance, 10 // 3 is 3, and 10 % 3 is 1.

Comparison Operators

These compare values and give me a boolean:

  • == : Equal to
    Example: 5 == 5 → True
  • != : Not equal to
    Example: 5 != 3 → True
  • > : Greater than
    Example: 5 > 3 → True
  • < : Less than
    Example: 5 < 3 → False
  • >= : Greater than or equal to
    Example: 5 >= 5 → True
  • <= : Less than or equal to
    Example: 5 <= 3 → False

These are perfect for checking conditions, like whether a user’s age is over 18.

Logical Operators

When I need to combine conditions, logical operators step in:

  • and: True if both are true
    Example: 5 > 3 and 10 < 20 → True
  • or: True if at least one is true
    Example: 5 < 3 or 10 < 20 → True
  • not: Flips the value
    Example: not True → False

Here’s a quick example I tried:

is_sunny = True
if not is_sunny:
    print("It’s cloudy!")
else:
    print("Enjoy the sun!")

Since is_sunny is Truenot is_sunny is False, so I get “Enjoy the sun!”

Operators give me the power to calculate, compare, and decide—essential skills for any program.


Assignment Operators: Updating Variables Efficiently

I often need to change a variable’s value, and assignment operators make it quick and clean. They combine an operation with assignment in one step.

Here’s a rundown:

  • = : Basic assignment
    Example: score = 10
  • += : Add and assign
    Example: score += 5 → score becomes 15
  • -= : Subtract and assign
    Example: score -= 3 → score becomes 12
  • *= : Multiply and assign
    Example: score *= 2 → score becomes 24
  • /= : Divide and assign
    Example: score /= 4 → score becomes 6.0
  • //= : Floor divide and assign
    Example: score //= 2 → score becomes 3
  • %= : Modulus and assign
    Example: score %= 2 → score becomes 1
  • **= : Exponentiate and assign
    Example: score **= 2 → score becomes 1

Let’s see it in action:

points = 50
points += 10  # points is now 60
points *= 3   # points is now 180

Instead of writing points = points + 10, I use +=—it’s shorter and just as clear.

These operators shine in loops (which we’ll explore later), but for now, they’re a neat trick to keep my code concise.


Mini Projects: Putting It All Together

Now that we’ve got the basics down, let’s apply them in two mini projects. These are hands-on ways for me to test my skills and see Python in action.

Mini Project 1: Simple Calculator

I decided to build a calculator that adds two numbers. Here’s my code:

print("Welcome to my additions calculator!")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 + num2
print(f"Your result is {result}")

How It Works:

  • I greet the user with a print() statement.
  • I use input() to get two numbers, but since input() gives strings, I cast them to int() with int().
  • I add num1 and num2 and store the sum in result.
  • I display the result with an f-string, which lets me embed result right in the message.

If I didn’t cast to int(), entering 2 and 3 would give "23" instead of 5. Type casting saves the day!

Mini Project 2: E-commerce Cart

Next, I built a simple e-commerce cart to calculate a total cost:

usr_name = input("May I know your name: ")
item = input("Please enter product name: ")
price = float(input("What is the price: "))
qty = int(input("How many qty are you looking for: "))
results = price * qty
print(f"Thank you {usr_name} for purchasing {item}, your net price is {results}$")

How It Works:

  • I collect the user’s name and product name as strings—no casting needed.
  • For price, I use float() since prices often have decimals.
  • For qty, I use int() because quantities are whole numbers.
  • I multiply price by qty to get results.
  • I use an f-string to create a friendly, personalized output.

Running this, if I enter “Alice”, “Laptop”, “999.99”, and “2”, I get:
“Thank you Alice for purchasing Laptop, your net price is 1999.98$”. It’s satisfying to see everything come together!

These projects showed me how variables, data types, operators, and type casting work in real scenarios. Let’s keep the momentum going with some exercises.


Coding Exercises: Practice Makes Perfect

Practice is how I turn knowledge into skills, so here are 10 exercises for us to try. I encourage you to write the code yourself and test it out!

  1. Greeting: Create a variable name with your name. Print “Hello, [name]!” using an f-string.
  2. Math Basics: Set x = 20 and y = 4. Calculate and print their sum, difference, product, and quotient.
  3. Voting Check: Ask the user for their age and print whether they can vote (age >= 18).
  4. Circle Area: Set pi = 3.14159 and radius = 7. Calculate and print the area (pi * radius ** 2).
  5. Comparison: Take two numbers from the user and print if the first is greater than, less than, or equal to the second.
  6. Weather: Set is_raining to True or False. Print “Take an umbrella” if true, else “Enjoy the sunshine”.
  7. Safe Division: Take two numbers and print their division result. Handle division by zero with a message.
  8. Temperature: Convert Celsius to Fahrenheit from user input. Use F = (C * 9/5) + 32.
  9. Even or Odd: Take a number and print if it’s even or odd (use %).
  10. Palindrome: Take a string and check if it’s a palindrome (e.g., “radar” vs “hello”).

These exercises cover everything we’ve learned today. I’ll try a few myself to make sure I’ve got it down.


Conclusion:

Wow, we’ve covered a lot today! I feel more confident now that I’ve mastered variablesdata typestype castingoperators, and assignment operators. Building the calculator and e-commerce cart was a blast—it’s amazing how a few lines of code can do so much. The exercises are a great way for me to keep practicing and reinforce what I’ve learned.

Looking ahead, I’m excited for Day 3, where we’ll dive into control structures like if statements and loops. These will let me make decisions and repeat tasks in my code, opening up even more possibilities. If you’re enjoying this journey as much as I am, stick with me—there’s so much more to explore.

Happy coding, everyone.

Read Also:

Python for Data Engineers & Data Analysts – Day 1: Learn Python from Scratch

Top 13 FREE Data Analysis Courses with Certifications

Leave a comment