Python - Data Types

Welcome, aspiring programmers! Today, we're diving into the fascinating world of Python data types. As your friendly neighborhood computer science teacher, I'm excited to guide you through this essential aspect of Python programming. So, grab your virtual notebook, and let's embark on this journey together!

Python - Data Types

Data Types in Python

In programming, data types are like different containers for storing various kinds of information. Imagine you're organizing a party, and you need different types of containers for different items - plates for food, glasses for drinks, and boxes for gifts. Similarly, in Python, we use different data types to store different kinds of data.

Let's start with a simple example:

name = "Alice"
age = 25
height = 5.7
is_student = True

In this code snippet, we've used four different data types:

  • name is a string (text)
  • age is an integer (whole number)
  • height is a float (decimal number)
  • is_student is a boolean (True or False)

Each of these variables holds a different type of data, just like how we use different containers for different items at our party.

Types of Python Data Types

Python comes with several built-in data types. Let's explore them one by one:

1. Numeric Types

a. Integer (int)

Integers are whole numbers, positive or negative, without decimals.

my_age = 30
temperature = -5

Here, both my_age and temperature are integers. You can perform various mathematical operations with integers:

x = 10
y = 3
print(x + y)  # Addition: 13
print(x - y)  # Subtraction: 7
print(x * y)  # Multiplication: 30
print(x / y)  # Division: 3.3333... (Note: This actually returns a float)
print(x // y) # Floor division: 3 (Rounds down to the nearest integer)
print(x % y)  # Modulus (remainder): 1
print(x ** y) # Exponentiation: 1000

b. Float

Floats are numbers with decimal points.

pi = 3.14159
gravity = 9.81

Floats can be used in calculations just like integers:

radius = 5
area = pi * (radius ** 2)
print(f"The area of the circle is {area:.2f}")  # Output: The area of the circle is 78.54

c. Complex

Complex numbers have a real and an imaginary part, denoted by 'j'.

z = 2 + 3j
print(z.real)  # Output: 2.0
print(z.imag)  # Output: 3.0

2. Sequence Types

a. String (str)

Strings are sequences of characters, enclosed in single or double quotes.

greeting = "Hello, World!"
name = 'Alice'
multi_line = """This is a
multi-line
string."""

Strings have many useful methods:

message = "Python is awesome"
print(message.upper())  # Output: PYTHON IS AWESOME
print(message.split())  # Output: ['Python', 'is', 'awesome']
print(len(message))     # Output: 20 (length of the string)

b. List

Lists are ordered, mutable sequences, denoted by square brackets.

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, [4, 5]]

Lists are versatile and allow various operations:

fruits.append("orange")  # Add an item
fruits.remove("banana")  # Remove an item
print(fruits[0])         # Access by index: apple
print(fruits[-1])        # Last item: orange
print(fruits[1:3])       # Slicing: ['cherry', 'orange']

c. Tuple

Tuples are ordered, immutable sequences, denoted by parentheses.

coordinates = (4, 5)
rgb = (255, 0, 128)

Tuples are similar to lists but can't be modified after creation:

print(coordinates[0])  # Access by index: 4
# coordinates[0] = 6   # This would raise an error

3. Mapping Type: Dictionary (dict)

Dictionaries store key-value pairs, denoted by curly braces.

person = {
    "name": "Bob",
    "age": 30,
    "city": "New York"
}

Dictionaries are extremely useful for structured data:

print(person["name"])   # Access by key: Bob
person["job"] = "Developer"  # Add a new key-value pair
del person["age"]       # Remove a key-value pair
print(person.keys())    # Get all keys
print(person.values())  # Get all values

4. Set Types

a. Set

Sets are unordered collections of unique elements, denoted by curly braces.

fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}

Sets are great for removing duplicates and set operations:

fruits.add("orange")
fruits.remove("banana")
print("apple" in fruits)  # Check membership: True

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2))        # Union: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Intersection: {3}

b. Frozenset

Frozensets are immutable sets.

fs = frozenset([1, 2, 3])
# fs.add(4)  # This would raise an error

Python Data Type Conversion

Sometimes, you need to convert data from one type to another. Python provides built-in functions for this purpose:

# String to Integer
age_str = "25"
age_int = int(age_str)
print(age_int + 5)  # Output: 30

# Integer to String
number = 42
number_str = str(number)
print("The answer is " + number_str)  # Output: The answer is 42

# String to Float
price_str = "19.99"
price_float = float(price_str)
print(price_float * 2)  # Output: 39.98

# List to Set (removes duplicates)
numbers = [1, 2, 2, 3, 3, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)  # Output: {1, 2, 3, 4, 5}

Data Type Conversion Functions

Here's a handy table of commonly used data type conversion functions:

Function Description Example
int(x) Converts x to an integer int("10")10
float(x) Converts x to a float float("3.14")3.14
str(x) Converts x to a string str(42)"42"
list(x) Converts x to a list list("hello")['h', 'e', 'l', 'l', 'o']
tuple(x) Converts x to a tuple tuple([1, 2, 3])(1, 2, 3)
set(x) Converts x to a set set([1, 2, 2, 3]){1, 2, 3}
dict(x) Creates a dictionary. x must be a sequence of key-value pairs dict([('a', 1), ('b', 2)]){'a': 1, 'b': 2}
bool(x) Converts x to a Boolean value bool(1)True, bool(0)False

Remember, these functions don't change the original value; they create a new value of the desired type.

And there you have it, dear students! We've journeyed through the land of Python data types, from the simple integers to the complex dictionaries. Each data type is a powerful tool in your programming toolbox, ready to help you solve various problems.

As you continue your Python adventure, you'll find yourself using these data types daily. They're the building blocks of your programs, the ingredients of your coding recipes. So, play around with them, experiment, and most importantly, have fun!

Remember, in programming, as in life, it's not about getting it right the first time. It's about learning, growing, and enjoying the process. So, don't be afraid to make mistakes – they're just stepping stones on your path to becoming a Python master!

Now, go forth and code! And always remember: in Python, as in life, type matters! ?✨

Credits: Image by storyset