If you’re new to Python, one of the first things you’ll encounter is variables and data types. Understanding how Python handles data is essential for writing clean, efficient, and bug-free programs. This guide breaks everything down step by step, from variable naming rules to advanced concepts like mutability, truthiness, type conversion, and best practices.

Whether you’re just starting with Python or refreshing your knowledge, this tutorial will help you master the fundamentals and avoid common mistakes.

1. What You’ll Learn

By the end of this guide, you will know how to:

  • Declare and name variables properly.
  • Work with Python’s built-in data types.
  • Understand the difference between identity vs equality.
  • Recognize mutable vs immutable objects.
  • Use truthy vs falsy values effectively.
  • Safely convert between types without errors.
  • Apply unpacking, comprehensions, and type hints.

2. Variables in Python: Names, Assignment, and Reassignment

2.1 Naming Rules and Style

Python has clear naming conventions:

  • Must begin with a letter or _, followed by letters, digits, or underscores.
  • Case-sensitive (age and Age are different).
  • Follow PEP 8 style:
    • Use snake_case for variables.
    • Use UPPER_SNAKE_CASE for constants.
READ 👉  Boosting App and Game Performance by Optimizing RAM on Windows 11

✅ Correct: total_count, max_items, API_KEY
❌ Avoid: 1stItem, TotalCount, __hidden_var__

2.2 Assignment Examples

x = 10          # create a variable
x = x + 5       # reassign
name = "Ava"
price, qty = 9.99, 3  # multiple assignment
a = b = 0            # chain assignment

2.3 Dynamic Typing

Python infers the variable type at runtime:

n = 5       # int
n = "five"  # now str

This flexibility is powerful, but you should use descriptive names and type hints for clarity.

3. Python Data Types (Cheat Sheet)

CategoryTypesMutable?Common Uses
Null/BoolNone, boolN/A/No“no value”, flags
Numbersint, float, complexNomath, counting, measurements
Text/Bytesstr, bytes, bytearrayNo/No/Yestext, binary data
Sequenceslist, tuple, rangeYes/No/Nocollections, fixed records, iteration
Setsset, frozensetYes/Nomembership, deduplication
MappingdictYeskey-value storage

💡 Pro tip: Mutable means the contents of the object can change without changing its identity.

4. Numbers in Python

  • Integers (int): unlimited precision.
  • Floats (float): double precision, but subject to rounding errors.
  • Complex (complex): support real and imaginary numbers.

Example:

from decimal import Decimal

0.1 + 0.2 == 0.3   # False due to floating point
Decimal("0.1") + Decimal("0.2") == Decimal("0.3")  # True

5. Booleans and None

ok = True
failed = False
result = None

Always check with is None instead of == None.

6. Strings (str)

Python strings are immutable.

s = "Python"
s.upper()        # 'PYTHON'
s[::-1]          # 'nohtyP'
f"Hello {s}"     # f-string formatting

7. Lists, Tuples, and Ranges

  • Lists: mutable collections.
  • Tuples: immutable, great for records.
  • Ranges: efficient, used in loops.
nums = [1, 2, 3]
nums.append(4)

point = (10, 20)
for i in range(3):  # 0, 1, 2
    print(i)

8. Dictionaries and Sets

  • Dicts (dict) store key-value pairs.
  • Sets (set) store unique elements.
user = {"id": 42, "name": "Ava"}
tags = {"python", "data", "python"}  # {'python', 'data'}

9. Bytes and Bytearray

Used for working with binary data:

data = "café".encode("utf-8")
bytearray(data)

10. Identity vs Equality

a = [1, 2]
b = a
a is b       # True (same object)
a == b       # True (same content)

11. Truthy and Falsy Values

Falsy values include:
False, None, 0, 0.0, 0j, "", [], {}, set(), range(0)

Everything else is truthy.

READ 👉  How to Convert a String to an Integer in Python (With Examples)

12. Safe Type Conversion

int("42")        # 42
float("3.14")    # 3.14
str(123)         # '123'

Use try/except to prevent crashes.

13. Unpacking and Swapping

x, y = 1, 2
x, y = y, x  # swap
head, *mid, tail = [1, 2, 3, 4, 5]

14. Comprehensions

squares = [n*n for n in range(10)]
evens = {n for n in range(10) if n % 2 == 0}

15. Scope: LEGB Rule

Order: Local → Enclosing → Global → Built-in

x = 10
def outer():
    x = 20
    def inner():
        nonlocal x
        x += 1
        return x
    return inner()

16. Mutability and Function Defaults

❌ Don’t use mutable defaults.
✅ Use None as a safe sentinel.

17. Type Hints

from typing import List, Dict, Optional

def find_user(users: list[dict], name: str) -> Optional[dict]:
    ...

18. Mini-Exercises

Practical tasks include:

  • Converting mixed prices to floats.
  • Word frequency counter with dict and set.
  • Shallow vs deep copy demonstration.

19. Common Mistakes to Avoid

  • Using == None instead of is None.
  • Mutable defaults in functions.
  • Assuming floats are exact.
  • Confusing is with ==.

20. Python Best Practices

  • Use clear variable names.
  • Prefer immutable data when possible.
  • Validate inputs early.
  • Use type hints for clarity.

21. Quick Reference

n: int = 42
s: str = "hello"
items: list[int] = [1, 2, 3]
user: dict[str, str] = {"name": "Ava"}

FAQ

Q: Do I need to declare variable types?
No, Python is dynamically typed.

Q: List vs Tuple?
Use a list for changing collections, a tuple for fixed ones.

Q: Why does 0.1 + 0.2 != 0.3?
Floating-point rounding.

Suggested Resources

Conclusion

Mastering variables and data types in Python is the first step to becoming a confident programmer. Once you understand how Python stores data, handles mutability, and applies type conversions, you’ll be able to write cleaner, safer, and more efficient code. Keep experimenting with the examples in this guide, and soon these concepts will feel second nature.

READ 👉  How to Disable On-Screen Keyboard Sound in Windows 11
Did you enjoy this article? Feel free to share it on social media and subscribe to our newsletter so you never miss a post!

And if you'd like to go a step further in supporting us, you can treat us to a virtual coffee ☕️. Thank you for your support ❤️!
Buy Me a Coffee

Categorized in: