By the end of this lesson, you will be able to write basic Python scripts using variables, understand core data types, and apply correct syntax for simple data manipulation tasks.
What it is
Python is a high-level, interpreted programming language known for its readability. In data analytics, it serves as the primary tool for cleaning, transforming, and analyzing datasets. The fundamental building blocks are variables (named containers for storing data) and types (the classification of that data). Common types includeint (whole numbers), float (decimal numbers), str (text strings), and bool (True/False values). Unlike some languages, Python uses dynamic typing, meaning you do not need to declare the type explicitly; the interpreter infers it upon assignment.
Why it matters
- Rapid Prototyping: Simple syntax allows analysts to test hypotheses quickly without boilerplate code.
- Data Integrity: Understanding types prevents errors like trying to perform math on text strings.
- Library Integration: Core Python skills are prerequisites for using powerful libraries like Pandas and NumPy.
- Readability: Clean code makes collaboration easier and reduces debugging time in complex pipelines.
Syntax or steps
1. Assignment: Use the equals sign (=) to assign a value to a variable name. Variable names should be descriptive and use snake_case (e.g., total_sales).
2. Comments: Use the hash symbol (#) to add notes that the interpreter ignores.
3. Type Checking: Use the built-in function type() to inspect what kind of data a variable holds.
4. Conversion: Use functions like int(), float(), or str() to change data types when necessary.
Example
# Define variables with different types
revenue = 50000 # int
growth_rate = 0.15 # float
category = "Electronics" # str
is_active = True # bool
# Perform a calculation
projected_revenue = revenue * (1 + growth_rate)
# Output results
print(f"Category: {category}")
print(f"Projected Revenue: ${projected_revenue:.2f}")
print(f"Data Type of Growth Rate: {type(growth_rate)}")
Explanation:
The script assigns four distinct values to variables. It then calculates projected_revenue by multiplying the integer revenue by a factor derived from the float growth_rate. Finally, it prints formatted output. Note how f-string formatting handles the decimal precision automatically.
Common mistakes
- Case Sensitivity:
Revenueandrevenueare treated as two different variables. Always stick to one naming convention. - Implicit Concatenation Errors: Trying to add a string and an integer directly (e.g.,
"Total: " + 5) raises a TypeError. Convert the number to a string first usingstr(5). - Reserved Keywords: Do not use words like
class,def, orifas variable names. - Indentation Errors: Python relies on whitespace to define blocks of code. Mixing tabs and spaces can cause unexpected crashes.
When to use it
Basic Python syntax is used for all initial data handling. Compare it with SQL for context:| Feature | Python Basics | SQL |
|---|---|---|
| Best For | Complex logic, custom calculations, API integration | Filtering, aggregating, joining large tables |
| Execution | Procedural (step-by-step) | Declarative (what result you want) |
| Data Location | Local memory or files | Database server |
Practice
Guided Exercise: Create a variable namedprice set to 19.99 and another named quantity set to 3. Calculate the total cost and print it with two decimal places.
Hint: Use total = price * quantity and print(f"Total: {total:.2f}").
Challenge: Take the string "1234" and convert it into an integer, then multiply it by 2. Print the result.
Hint: Use int("1234") before performing multiplication.
Quick check
Question: What happens if you try to executeprint("Age: " + 25)?
Answer: It raises a TypeError because Python cannot concatenate a string and an integer directly. You must convert the integer to a string first: print("Age: " + str(25)).