Think of data types as different kinds of containers you use to hold specific types of information in Python. Just like you use a cup for water, a bowl for soup, and a plate for food, Python has different "containers" for different kinds of data.
Basic data types
Strings str
str
A string is a collection of characters arranged in a specific order, like letters, numbers, symbols, or even spaces. It's essentially how Python handles and stores text-based data. Think of it as a way to represent words, phrases, sentences, or any sequence of characters that you might use in a program.
In Python, strings are created by enclosing the characters within either single quotes '
"
"Hello"
'Hello'
Examples:
name = "Alice"
greeting = 'Hello, world!'
Use case: When you need to store text, names, or messages.
Integers int
int
An integer is a whole number, meaning it has no fractional or decimal part. Integers can be positive, negative, or even zero. They are used to represent quantities, counts, or values where only whole numbers make sense, like the number of apples in a basket or a person’s age in years.
Integers are written as plain numbers without any decimal point or special symbols. For example, 42
-15
0
Examples:
age = 25
year = 2024
Use case: When you want to count things or work with whole numbers.
Floats float
float
A float, short for "floating-point number," is a number that can represent values with a decimal point. Floats are used when you need to work with more precise quantities, such as measurements, prices, or scientific data, where fractions of a number are important. Floats can be both positive and negative, and they include any number that isn't a whole number.
A float is written with a decimal point. For example, 3.14
-7.5
0.99
1.5e2
Examples:
price = 19.99
temperature = 36.5
Use case: When you need to work with measurements, prices, or calculations that need decimals.
Booleans bool
bool
A boolean is a data type that represents one of two possible values: True
False
Booleans are written as True
False
is_sunny = True
is_raining = False
if
while
Examples:
is_raining = False
has_ticket = True
Use case: When you want to check if something is true or false, like for making decisions in your program.
Why these data types matter
Python needs to know the type of data you're working with so it can handle it correctly. For example:
You can add integers 2 + 3
→ 5
"hello" + 5
→ error!