Mostly I don't share Python content on this blog but nowadays as I'm learning about Python. I have seen that it's a bit different when it comes to Python. Because it has a little bit different data t...
Gurpreet Kait
Author
Mostly I don't share Python content on this blog but nowadays as I'm learning about Python. I have seen that it's a bit different when it comes to Python. Because it has a little bit different data types we have seen them in other languages like javascript or PHP. But somehow they are different in pronunciation as well as their practical use.
This blog will dive into Python's essential data types with practical examples to help you grasp their usage in real-world scenarios. As usual, I'll focus on less theory and more practical.
Str Types
Text Type (str): The str data type in Python is used to handle text data. Let's see how it works in a practical example:
# Creating a string variable
message ="Hello, Python!"
# Accessing characters in the string
print(message) # Output:'H'
# Concatenating strings
new_message = message +" Welcome to Python!"
print(new_message) # Output:'Hello, Python! Welcome to Python!'
# String formatting
name ="Alice"
age = 30
formatted_message = f"My name is {name} and I am {age} years old."
print(formatted_message) # Output:'My name is Alice and I am 30 years old.'
Numeric Types
Python supports various numeric data types for handling numerical data. Here's a practical example:
We use sequences to store collections of items. Let's explore them with an example:
# Listmy_list =
# Tuplemy_tuple = (10, 20, 30)
# Rangemy_range = range(1, 10)
# Accessing elements in the list and tupleprint(my_list) # Output: 1print(my_tuple) # Output: 20# Iterating through a rangefor num in my_range:
print(num) # Outputs numbers from 1 to 9
Note: If you want to print the range you have to use list() function.
We use sets to store unique elements. Here's how you can use sets in Python:
# Setmy_set = {1, 2, 3, 4}
# Adding elements to a setmy_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}
Boolean Type (bool):
Well, this type is very common. In Python, you just capitalize false and true. We use Booleans for logical operations and conditions. Let's see a practical example:
# Boolean
is_active = True
is_valid = False# Conditional statementsif is_active:
print("User is active")
else:
print("User is inactive")
Binary Types (bytes, bytearray, memoryview):
Binary data types are used for handling binary data. Here's a simple example:
Mastering Python's data types is essential for writing efficient and effective code. By practicing with these examples and understanding how each data type works, you'll be better equipped to tackle real-world programming challenges in Python. Happy coding!