Learn about data types in Python, which define the nature of data stored in variables. Understand strings, integers, floats, and booleans with easy-to-follow examples.
Data Types in Python
Overview of Data Types
Data types are like labels that tell Python what kind of information is being stored in a variable. They help Python understand how to handle that data when performing operations like math, comparisons, or text processing.
Quick Quiz: Data Types Basics
What is the purpose of data types in Python?
1. String (str
)
A string is a type of data that holds text. Strings are created by placing text inside single quotes (' '
), double quotes (" "
), or triple quotes (''' '''
or """ """
).
# Example of a string
name = "Alice" # Using double quotes
greeting = 'Hello!' # Using single quotes
multiline_text = """This is
a multiline string.""" # Using triple quotes
# Simple string operations
print(name) # Output: Alice
print(greeting + " " + name) # Output: Hello! Alice
Tip: Strings can be combined using the +
operator (called concatenation) and repeated using the *
operator.
String Quiz
Which of these is NOT a valid way to create a string?
What does print("Hi" * 3)
output?
2. Integer (int
)
An integer is a whole number, meaning it has no decimal point. Integers can be positive, negative, or zero.
# Example of integers
age = 25 # Positive integer
negative_number = -10 # Negative integer
zero = 0 # Zero
# Simple integer operations
print(age + 5) # Output: 30
print(negative_number - 2) # Output: -12
Tip: You can do arithmetic with integers using operators like +
, -
, *
(multiply), and /
(divide).
Integer Quiz
What is the result of 7 // 2
(floor division)?
Which of these is NOT an integer?
3. Float (float
)
A float is a number with a decimal point. Floats are useful when you need precision, such as with measurements or currency.
# Example of floats
height = 5.8 # Positive float
temperature = -20.5 # Negative float
pi = 3.14159 # Common mathematical constant
# Simple float operations
print(height * 2) # Output: 11.6
print(pi + 1) # Output: 4.14159
Tip: Floats can handle fractions and support the same arithmetic operations as integers.
Float Quiz
What is the type of 4.0
?
What does 0.1 + 0.2
return in Python?
4. Boolean (bool
)
A boolean represents one of two values: True
or False
. Booleans are often used to make decisions in code using conditions.
# Example of booleans
is_student = True # Boolean representing truth
has_permission = False # Boolean representing falsehood
# Simple boolean usage
print(is_student) # Output: True
print(has_permission) # Output: False
# Using booleans in conditions
if is_student:
print("Welcome, student!") # Output: Welcome, student!
else:
print("Access denied.")
Tip: Booleans are used in comparisons and logical operations like and
, or
, and not
.
Boolean Quiz
What is the result of not True
?
What does 5 > 3 and 2 < 4
evaluate to?