PythonProgramming Basics

Python Data Types: The Building Blocks of Your Code

TT
TopicTrick
Python Data Types: The Building Blocks of Your Code

Introduction to Python Data Types

Welcome to this foundational Python tutorial on Data Types. A data type specifies the kind of value a variable holds (e.g., an integer, a decimal, or text). Understanding these building blocks is crucial for writing efficient and bug-free code.

In Python, data types are broadly categorized into two types:

  1. Built-in Data Types (provided by Python itself).
  2. User-Defined Data Types (created by you, the programmer).

The Beauty of Dynamic Typing

In older programming languages like C or Java, you have to explicitly declare the type of a variable before using it (e.g., int age = 30;). Python is a dynamically typed language, meaning it figures out the data type automatically based on the value you assign.

python
1age = 33 # Python assigns the 'int' tag 2name = "John" # Python assigns the 'str' tag

If you reassign a new value of a different type, Python handles the memory management automatically using its garbage collector.

python
1age = "Thirty Three" # Now it's a 'str'. The old 'int' tag is removed.

Built-In Data Types

Python comes with several powerful built-in data types, ready to use out of the box.

1. Numeric Types

Used to store mathematical values.

  • int (Integer): Whole numbers, positive or negative, without decimals (e.g., 10, -3).
  • float: Real numbers with a floating-point representation (e.g., 10.5, -3.14).
  • complex: Complex numbers with a real and imaginary part (e.g., 3 + 5j).

2. Boolean Type (bool)

Represents truth values. It can only be True or False. Internally, these evaluate to 1 and 0. Empty strings "", lists [], and zero itself evaluate to False.

3. Sequence Types

Used to store multiple items in a specific order.

  • str (String): Text data wrapped in quotes (e.g., "TopicTrick").
  • list: A mutable (changeable) collection of items (e.g., [1, "Apple", 3.14]).
  • tuple: An immutable (unchangeable) collection of items (e.g., (1, "Apple", 3.14)).
  • range: A sequence of numbers, often used in loops.

4. Sets (set, frozenset)

Unordered collections of unique elements. Sets do not allow duplicate values and are highly optimized for checking if an item exists within them.

5. Mapping Type (dict)

A Dictionary stores data in key: value pairs, similar to a real-world dictionary. It's optimized for retrieving data quickly based on a unique key.

Examples in Action:

python
1# Numeric 2a = 12 # int 3c = 12.22 # float 4d = -1 + 5j # complex 5 6# Boolean 7is_active = True # bool 8 9# Sequence 10text = "topictrick" # str 11my_list = [10, 20] # list 12my_tuple = (1, 2) # tuple 13 14# Mapping & Set 15my_dict = {"name": "Harry", "age": 25} # dict 16my_set = {10, 20, 30} # set

User-Defined Data Types

When built-in types aren't enough, you can create your own structures using Classes. These are custom blueprints for creating objects that hold specific data and behaviors needed for your application.

Learn more about OOP

To dive deep into User-Defined Data Types, check out our tutorial on [Object-Oriented Programming in Python](https://topictrick.com/oop-in-python-overview/).


    Important Concepts

    1. Naming Conventions (Identifiers)

    An identifier is a name given to variables, functions, or classes.

    • Use snake_case for variables and functions (e.g., total_price).
    • Use PascalCase for classes (e.g., UserProfile).
    • Use ALL_CAPS for constants (e.g., MAX_RETRIES).
    • Must not start with a number.

    2. Reserved Keywords

    Words like if, else, while, True, def, and class are reserved by Python and cannot be used as variable names.

    3. Escape Characters in Strings

    Sometimes you need to include special characters inside a string.

    CharacterDescriptionExample Output
    \\nNew LineStarts a new line
    \\tTabAdds horizontal space
    \\\\BackslashPrints a literal \\
    \\' Single QuotePrints a literal '

    Comments & Docstrings

    Single-line comments start with a #.

    python
    1# This calculates the total tax 2tax = price * 0.2

    Docstrings use triple quotes (""" or '''). They are used right after defining a function or class to describe what it does. They are not ignored by Python but are attached to the function's __doc__ attribute.

    python
    1def calculate_total(a, b): 2 """ 3 Returns the sum of parameter a and parameter b. 4 """ 5 return a + b

    Conclusion

    Understanding Python's data types is your first major step toward writing functional code. Python's dynamic typing makes it incredibly easy to start coding quickly, while its rich set of built-in structures (lists, dicts, sets) provides immense power for managing data.

    Keep practicing, and you'll be manipulating complex data structures in no time!