Variables & Data Types
Variables and Data Types in Python
Variables are containers for storing data values. In Python, you don't need to declare variables before using them or declare their type.
Python automatically determines the variable's data type based on the value assigned to it.
1. Primitive Data Types
Python has several built-in primitive data types:
Integers (int)
Whole numbers, positive or negative, without decimals.
age = 25
temperature = -5
Floating-point numbers (float)
Numbers with decimal points or in exponential form.
pi = 3.14159
avogadro = 6.022e23 # Scientific notation
Strings (str)
Sequences of characters, enclosed in single or double quotes.
name = "Alice"
message = 'Hello, World!'
multiline = """This is a
multiline string."""
Booleans (bool)
Represents True or False values.
is_python_fun = True
is_raining = False
None
Represents the absence of a value or a null value.
result = None
2. Composite/Compound Data Types
Composite data types are collections of other data types:
Lists
Ordered, mutable sequences of elements.
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "two", 3.0, True]
Tuples
Ordered, immutable sequences of elements.
coordinates = (10, 20)
rgb = (255, 0, 128)
Dictionaries
Unordered collections of key-value pairs.
person = {
"name": "Bob",
"age": 30,
"city": "New York"
}
Sets
Unordered collections of unique elements.
unique_numbers = {1, 2, 3, 4, 5}
vowels = set(['a', 'e', 'i', 'o', 'u'])
Type Conversion and Type Casting
Python allows you to convert between different data types:
Implicit Type Conversion
Python automatically converts one data type to another if needed.
x = 5
y = 2.0
result = x + y # result will be a float (7.0)
Explicit Type Conversion (Type Casting)
You can manually convert between types using built-in functions.
# String to Integer
age_str = "25"
age_int = int(age_str) # 25
# Integer to String
number = 42
number_str = str(number) # "42"
# String to Float
price_str = "19.99"
price_float = float(price_str) # 19.99
# Float to Integer (truncates decimal part)
height = 1.75
height_int = int(height) # 1
# Integer to Float
count = 10
count_float = float(count) # 10.0
# String to List
word = "Python"
char_list = list(word) # ['P', 'y', 't', 'h', 'o', 'n']
# List to Set (removes duplicates)
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(numbers) # {1, 2, 3, 4, 5}
Remember that not all type conversions are possible, and some may result in loss of information or raise exceptions if the conversion is invalid.