python

Data Types in Python


In programming, a data type is a classification that specifies which type of value a variable can hold. Python, being a dynamically typed language, allows variables to change their data type during runtime, providing flexibility without sacrificing readability.

1. Numeric Types:
Python supports various numeric types, including integers, floats, and complex numbers. Let's delve into a few examples:

# Integers
age = 25

# Floats
height = 5.9

# Complex Numbers
complex_num = 3 + 4j

 

2.  String Type:
Strings are sequences of characters and play a crucial role in handling textual data. Here's a glimpse of string manipulation in Python:

greeting = "Hello, Python!"

# String concatenation
full_greeting = greeting + " You are amazing!"

# String slicing
substring = greeting[7:13]

 

3. List Type:
Lists are versatile, allowing the storage of multiple values in a single variable. They are mutable and can contain elements of different data types:

fruits = ["apple", "banana", "orange"]

# Adding elements to the list
fruits.append("grape")

# Accessing elements
second_fruit = fruits[1]

 

4. Tuple Type:
Tuples are similar to lists but are immutable, meaning their elements cannot be modified after creation:

coordinates = (3, 4)

# Unpacking tuple
x, y = coordinates

 

5. Dictionary Type:
Dictionaries store key-value pairs, enabling efficient data retrieval:

person = {"name": "Alice", "age": 30, "city": "Wonderland"}

# Accessing values
alice_age = person["age"]

# Adding a new key-value pair
person["occupation"] = "Software Engineer"

 

6. Set Type:
Sets are unordered collections of unique elements, offering powerful operations like union and intersection:

prime_numbers = {2, 3, 5, 7, 11}

# Adding elements to a set
prime_numbers.add(13)

# Set operations
odd_numbers = {3, 5, 7, 9}
common_odd_primes = prime_numbers.intersection(odd_numbers)

python