TL ; DR:
In Python, not all data is treated the same. There are different data types, such as:
int
- represents integer numbers like 3
and -12
float
- represents floating point numbers like 3.14
str
- represents a string (sequence of characters) like "John Doe"
bool
- represents a Boolean, data that can have one of two values: True
or False
None
- represents a null value, or no value at all
Full lesson:
We've talked about data and variables, which are containers to store that data. But not all data is treated the same.
For example, Python distinguishes between numbers, such as the number 12
, and strings, such as "12"
or "dog"
, which are collections of characters.
The most basic and used data types in Python are:
int
- represents integer numbers like 3
and -12
float
- represents floating point numbers like 3.14
str
- represents a string (sequence of characters) like "John Doe" or 'dog'
bool
- represents a Boolean, data that can have one of two values: True or False
None
- represents a null value, or no value at all
type() function
Python knows what type everything is. We can ask Python what type something is by using the type() function:
x = 1
print(type(x)) # Output: <class 'int'>
y = 3.14
print(type(y)) # Output: <class 'float'>
print(type("butter")) # Output: <class 'str'>
z = True
print(type(z)) # Output: <class 'bool'>
temp = 23.0
print(type(temp)) # Output: <class 'float'>
Choosing what operation to perform:
One instruction can have several distinct meanings depending on the data types it's working with.
For example, suppose you see this line of code somewhere in a program:
print(a + b)
Can you tell for sure what it does without knowing anything about the variables a
and b
?
It might add two numbers, if a
and b
are both numbers:
a = 10
b = -5
print(a + b) # Output: 5
But it also might concatenate two strings, if a
and b
are both strings:
a = "Hello "
b = "world!"
print(a + b) # Output: Hello world!
Of course, addition and string concatenation are two completely different operations and Python needs to figure out which one to do.
And this is exactly why Python assesses the data type of every value you use in your program. In order to be able to make these decisions when needed.
In our example, when it reads a + b
, Python checks the data type of a
and b
. If both are string, it performs string concatenation. If both are numbers, it performs addition.
Invalid operations:
Asessing data types is also helpful for Python to make sure that what you do with the data actually makes sense.
For example, computers can perform mathematical operations on numbers, but not on strings. Of course, nobody can stop you from writing a program like this:
a = "peanut"
b = "butter"
print(a * b) # TypeError
But when you try to run this program, Python will throw a TypeError: can't multiply sequence by non-int of type 'str'
.
This is the way of Python telling you: "Hey, I'm a little confused. How do you multiply two strings? I've never heard of that."
Assignment
Follow the Coding Tutorial and let's practice with data types!
Hint
Look at the examples above if you get stuck.
Understanding data types is fundamental in programming. In Python, data types define the kind of value a variable can hold. This is crucial because different operations are valid for different data types. For instance, you can add two integers, but you cannot add an integer and a string directly. Knowing data types helps in writing error-free and efficient code.
Before diving into complex operations, it's essential to grasp the basic data types in Python:
int
: Represents integer numbers like 3
and -12
.float
: Represents floating-point numbers like 3.14
.str
: Represents strings, which are sequences of characters like "John Doe"
.bool
: Represents Boolean values, which can be either True
or False
.None
: Represents a null value, or no value at all.Understanding these basics is crucial as they form the foundation for more complex data structures and operations in Python.
Let's delve deeper into these data types and see how they work:
Integers (int
) are whole numbers, while floats (float
) are numbers with a decimal point. You can perform arithmetic operations on both:
# Integer operations
a = 10
b = 5
print(a + b) # Output: 15
print(a - b) # Output: 5
# Float operations
x = 3.14
y = 2.0
print(x * y) # Output: 6.28
print(x / y) # Output: 1.57
Strings (str
) are sequences of characters. You can concatenate strings using the +
operator:
a = "Hello"
b = "World"
print(a + " " + b) # Output: Hello World
Booleans (bool
) represent truth values. They are often used in conditional statements:
is_sunny = True
if is_sunny:
print("It's a sunny day!") # Output: It's a sunny day!
None
represents the absence of a value. It is often used to initialize variables or to signify that a variable is empty:
x = None
if x is None:
print("x is None") # Output: x is None
Let's look at some practical examples:
When taking user input, it's essential to convert the input to the correct data type:
age = input("Enter your age: ")
age = int(age) # Convert the input to an integer
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Performing calculations with different data types:
length = 5.0
width = 2
area = length * width # area will be a float
print("Area:", area) # Output: Area: 10.0
Here are some common mistakes to avoid and best practices to follow:
int()
, float()
, and str()
to convert between data types.Once you're comfortable with basic data types, you can explore more advanced concepts like:
Here's a comprehensive example demonstrating the use of different data types:
# Example demonstrating various data types
# Integer
age = 25
print("Age:", age) # Output: Age: 25
# Float
height = 5.9
print("Height:", height) # Output: Height: 5.9
# String
name = "Alice"
print("Name:", name) # Output: Name: Alice
# Boolean
is_student = True
print("Is student:", is_student) # Output: Is student: True
# None
address = None
print("Address:", address) # Output: Address: None
# Using type() function
print(type(age)) # Output:
print(type(height)) # Output:
print(type(name)) # Output:
print(type(is_student)) # Output:
print(type(address)) # Output:
Debugging and testing are crucial for ensuring your code works as expected:
unittest
or pytest
for automated testing.import unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add_integers(self):
self.assertEqual(add(1, 2), 3)
def test_add_floats(self):
self.assertEqual(add(1.1, 2.2), 3.3)
def test_add_strings(self):
self.assertEqual(add("Hello ", "World"), "Hello World")
if __name__ == "__main__":
unittest.main()
Here are some strategies for approaching problems related to data types:
Mastering data types in Python is essential for writing efficient and error-free code. By understanding the basics, avoiding common pitfalls, and practicing regularly, you can become proficient in handling different data types. Keep exploring and experimenting with advanced concepts to further enhance your skills.
Here are some additional resources to help you learn more about data types in Python: