Python – Data Types
Python supports several data types. The most common ones include:
- Numeric Types:
- Integer: Whole numbers, positive or negative, without decimals.
- Float: Numbers, positive or negative, containing one or more decimals.
- Complex: Complex numbers.
- Sequence Types:
- String: A sequence of characters.
- List: Ordered collection of items, can be of different types.
- Tuple: Ordered collection of items, immutable.
- Set Types:
- Set: Unordered collection of unique items.
- Frozen Set: Immutable set.
- Mapping Types:
- Dictionary: Collection of key-value pairs.
- Boolean Type:
- Boolean: Represents one of two values:
True
orFalse
.
- Boolean: Represents one of two values:
Rules for Naming Variables
- Must begin with a letter (a-z, A-Z) or an underscore (_)
- Cannot start with a number
- Can only contain alphanumeric characters and underscores (A-z, 0-9, and _)
- Case-sensitive (e.g.,
myVariable
andmyvariable
are different) - Cannot be a reserved keyword (e.g.,
if
,for
,while
)
Example:
# Valid variable names
name = "Alice"
age = 30
_height = 5.7
is_student = True
# Invalid variable names
1name = "Alice" # Starts with a number
name! = "Alice" # Contains an illegal character (!)
Numeric Types Examples
# Integer
age = 30
print(type(age)) # Output: <class 'int'>
# Floating-point
height = 5.7
print(type(height)) # Output: <class 'float'>
# Complex number
complex_num = 3 + 4j
print(type(complex_num)) # Output: <class 'complex'>
Sequence Types Examples
# Single quotes
name = 'Alice'
print(type(name)) # Output: <class 'str'>
# Double quotes
message = "Hello, World!"
print(type(message)) # Output: <class 'str'>
# Triple quotes (used for multi-line strings)
description = """This is a
multi-line string."""
print(type(description)) # Output: <class 'str'>
# List
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>
# Tuple
coordinates = (10.0, 20.0)
print(type(coordinates)) # Output: <class 'tuple'>
# Range
numbers = range(1, 10)
print(type(numbers)) # Output: <class 'range'>
Set Types Examples
# Set
unique_numbers = {1, 2, 3, 4, 4, 5}
print(type(unique_numbers)) # Output: <class 'set'>
# Frozenset
immutable_set = frozenset([1, 2, 3, 4, 5])
print(type(immutable_set)) # Output: <class 'frozenset'>
Mapping Type Examples
# Dictionary
person = {"name": "Alice", "age": 30, "is_student": True}
print(type(person)) # Output: <class 'dict'>
Boolean Type Example
bool: Represents True
or False
is_student = True
print(type(is_student)) # Output: <class 'bool'>