Thursday, 26 June 2025

Python Built-in Datatypes

🌟 Introduction to Built-in Datatypes

Ever wondered how computers understand different types of data like numbers, names, or even true/false questions? That's where datatypes come into play! They're like labels that tell the computer what kind of value you're working with.

🔍 What Are Datatypes?

In programming, a datatype tells the interpreter what kind of value a variable holds. It could be a number, a piece of text, a list of things, or even something more complex.

📌 Why Datatypes Matter in Programming

Imagine trying to add two names together or divide a word by a number—it wouldn't make any sense! That's why programming languages use datatypes to prevent errors and organize your code.

⚖️ Static vs Dynamic Typing

  • Static Typing: You must declare the datatype before using it (like in Java or C++)
  • Dynamic Typing: The interpreter figures it out for you (like in Python)

Python uses dynamic typing, so it automatically understands what kind of data you're using.

🧱 Built-in vs User-defined Datatypes

  • Built-in Datatypes: Already available in the language (no need to define them)
  • User-defined Datatypes: Created by programmers using classes and objects

In this article, we're focusing on the built-in ones.

🔢 Numeric Datatypes

These are used when you want to store numbers.

1. Integer (int)

Used to store whole numbers, like 10, -3, or 0.

age = 25

2. Float (float)

Used to store decimal numbers, like 3.14, -0.5, or 99.99.

pi = 3.14159

3. Complex (complex)

Used in advanced mathematics, includes a real and an imaginary part.

z = 2 + 3j

📚 Sequence Datatypes

A sequence is an ordered collection of items.

1. String (str)

Used to store text, written in quotes.

name = "Alice"

You can use:

  • len(name) → Number of characters
  • name.upper() → Convert to uppercase

2. List (list)

Used to store multiple items in one variable. Lists are mutable (you can change them).

fruits = ["apple", "banana", "mango"]
fruits.append("orange")

3. Tuple (tuple)

Similar to lists but immutable (cannot be changed).

coordinates = (10, 20)

🔘 Set Datatypes

Sets store unique items and do not maintain order.

1. Set (set)

numbers = {1, 2, 3, 3}
# Output: {1, 2, 3}

Useful for removing duplicates.

2. Frozen Set (frozenset)

An immutable version of a set.

fs = frozenset([1, 2, 3])

🗺️ Mapping Datatype

Dictionary (dict)

Stores data in key-value pairs.

student = {
  "name": "John",
  "age": 16,
  "grade": "A"
}

Access using keys:

print(student["name"])  # Output: John

✅ Boolean Datatype

Boolean (bool)

Has only two values: True or False.

is_logged_in = True

Commonly used in conditions and loops.

🚫 None Type

What is None?

None represents the absence of a value. It's like a blank placeholder.

result = None

You might use it when a variable is declared but not yet given a value.

🔄 Type Conversion and Type Casting

Sometimes you need to change one datatype into another.

Implicit Conversion

Python does it for you.

x = 5     # int
y = 2.5   # float
z = x + y  # float (Python converts int to float automatically)

Explicit Conversion

You do it manually.

x = 10
y = str(x)  # Convert int to string

🛠️ Built-in Functions for Datatypes

These make life easier:

  • type() → Returns the datatype
  • id() → Returns the memory address
  • isinstance() → Checks the type

Example:

num = 100
print(type(num))  # Output: <class 'int'>

🔁 Memory and Mutability

Mutable vs Immutable Types

  • Mutable: Can be changed (list, set, dict)
  • Immutable: Cannot be changed (int, float, str, tuple, frozenset)

Why does it matter? Because changing a mutable object affects its original reference.

💼 Real-Life Examples and Use-Cases

Using Lists to Store Marks

marks = [88, 76, 92, 85]

You can calculate average, highest marks, etc.

Using Dictionary for Employee Info

employee = {
  "name": "Ravi",
  "id": 103,
  "department": "HR"
}

You can easily update, search, and manage data using keys.

🏁 Conclusion

Built-in datatypes are the building blocks of every Python program. Whether you're dealing with numbers, names, lists of groceries, or a record of students, Python has a datatype ready for it. Understanding these core types will help you write efficient and error-free code. So, the next time you're coding, remember—you're not just typing lines; you're instructing the computer using these datatypes!

❓ FAQs

  • What is the difference between list and tuple?
    A list is mutable (you can change it), while a tuple is immutable (you can't change it once created).
  • Can a set have duplicate values?
    No, sets automatically remove duplicates.
  • What is the default datatype of a number like 5?
    It's an integer (int).
  • Why is None used in Python?
    To represent a variable with no value or to initialize a variable for future use.
  • Are Python datatypes case-sensitive?
    Yes, Python is case-sensitive. True is a valid Boolean, but true is not.

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...