Data Types
In Python, every value has a specific data type. Understanding these types is crucial for writing efficient programs.
Common Data Types in Python
1. Integer (int)
Whole numbers, both positive and negative.
age = 25
temperature = -10
2. Floating-Point Number (float)
Numbers with decimal points.
price = 10.99
gravity = 9.81
3. String (str)
A sequence of characters enclosed in quotes.
name = "Alice"
greeting = 'Hello, world!'
4. Boolean (bool)
Represents True or False values.
is_sunny = True
has_license = False
5. List (list)
An ordered collection of items.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
6. Tuple (tuple)
An immutable (unchangeable) ordered collection.
coordinates = (10, 20)
colors = ("red", "green", "blue")
7. Dictionary (dict)
A collection of key-value pairs.
person = {"name": "Alice", "age": 25, "city": "New York"}
8. Set (set)
An unordered collection of unique items.
unique_numbers = {1, 2, 3, 3, 4, 5} # {1, 2, 3, 4, 5}
Checking Data Types
We can check the type of a variable using type().
x = 10
print(type(x)) # Output: <class 'int'>
Exercise: Try It Yourself!
- Create a variable of each data type and print its type using
type(). - Convert a float to an integer using
int(9.8). What happens? - Try modifying a tuple. What error do you get?