Session Overview
Welcome to our deep dive into Python type conversion! In this session, we'll explore how to convert data between different types in Python, a crucial skill for working with inputs, processing data, and ensuring compatibility across operations. We'll cover implicit and explicit type conversions, understand when and why to use them, and learn best practices for handling type conversion in your programs.
Understanding Type Conversion
Type conversion (also called type casting) is the process of converting a value from one data type to another. Python provides two types of conversion:
- Implicit Type Conversion: Automatically performed by Python when needed
- Explicit Type Conversion: Manually performed by the programmer using built-in functions
Why Type Conversion is Important
Type conversion is necessary for many common programming scenarios:
- Converting user input (typically strings) to appropriate data types
- Performing operations between different data types
- Storing or processing data in specific formats
- Ensuring compatibility with external libraries and APIs
- Optimizing memory usage or performance
Analogy: Type Conversion as Language Translation
Think of data types as different languages. Each language has its own grammar, vocabulary, and rules:
- Implicit conversion is like having a translator automatically helping you understand a similar language
- Explicit conversion is like deliberately translating a document from one language to another
- Some translations are straightforward (like converting a number to a string)
- Others may lose information or nuance (like converting a float to an integer)
- Some translations are impossible without additional context (like converting an arbitrary string to a number)
Just as you need translation to communicate between languages, you need type conversion to operate between different data types in Python.
Implicit Type Conversion (Coercion)
Python automatically converts certain compatible types when needed, particularly in mixed-type operations. This is called implicit type conversion or type coercion.
Numeric Type Conversion
When performing operations with different numeric types, Python follows this conversion hierarchy:
int → float → complex
# Integer and Float in an operation
result = 10 + 5.5 # int + float = float
print(result) # 15.5
print(type(result)) # <class 'float'>
# Integer and Complex in an operation
result = 10 + 2j # int + complex = complex
print(result) # (10+2j)
print(type(result)) # <class 'complex'>
# Integer, Float, and Complex
result = 10 + 5.5 + 2j # int + float + complex = complex
print(result) # (15.5+2j)
print(type(result)) # <class 'complex'>
Boolean Type in Operations
In operations, boolean values are implicitly converted to integers (True becomes 1, False becomes 0):
# Boolean in arithmetic operations
result = 10 + True # True is converted to 1
print(result) # 11
# Boolean in arithmetic with float
result = 5.5 * False # False is converted to 0
print(result) # 0.0
# Boolean with boolean
result = True + True # Both converted to 1
print(result) # 2
Limitations of Implicit Conversion
Python does not implicitly convert between unrelated types:
# This will raise a TypeError
try:
result = "10" + 5
print(result)
except TypeError as e:
print(f"Error: {e}") # Error: can only concatenate str (not "int") to str
# This will also raise a TypeError
try:
result = [1, 2, 3] + 4
print(result)
except TypeError as e:
print(f"Error: {e}") # Error: can only concatenate list (not "int") to list
In these cases, you need to use explicit type conversion.
Explicit Type Conversion (Type Casting)
Explicit type conversion is performed by using built-in functions to convert a value from one type to another. Python provides several built-in functions for this purpose.
Converting to Integer (int())
# From float (truncates, doesn't round)
integer = int(7.8)
print(integer) # 7
# From string (must contain a valid integer representation)
integer = int("25")
print(integer) # 25
# From boolean
integer = int(True)
print(integer) # 1
# From other bases (binary, octal, hexadecimal)
binary = int("1010", 2) # Base 2
print(binary) # 10
octal = int("17", 8) # Base 8
print(octal) # 15
hexadecimal = int("1A", 16) # Base 16
print(hexadecimal) # 26
# Error cases
try:
integer = int("25.5") # Will fail - contains a decimal point
except ValueError as e:
print(f"Error: {e}") # Error: invalid literal for int() with base 10: '25.5'
try:
integer = int("hello") # Will fail - not a number
except ValueError as e:
print(f"Error: {e}") # Error: invalid literal for int() with base 10: 'hello'
Converting to Float (float())
# From integer
float_num = float(42)
print(float_num) # 42.0
# From string (can contain integer or decimal representation)
float_num = float("3.14")
print(float_num) # 3.14
float_num = float("25") # Integer string
print(float_num) # 25.0
# From boolean
float_num = float(False)
print(float_num) # 0.0
# Scientific notation
float_num = float("1.5e3") # Scientific notation for 1.5 × 10³
print(float_num) # 1500.0
# Special values
float_num = float("inf") # Infinity
print(float_num) # inf
float_num = float("-inf") # Negative infinity
print(float_num) # -inf
float_num = float("nan") # Not a Number
print(float_num) # nan
# Error cases
try:
float_num = float("3.14.15") # Will fail - too many decimal points
except ValueError as e:
print(f"Error: {e}") # Error: could not convert string to float: '3.14.15'
try:
float_num = float("hello") # Will fail - not a number
except ValueError as e:
print(f"Error: {e}") # Error: could not convert string to float: 'hello'
Converting to String (str())
The str() function can convert virtually any Python object to a string representation:
# From integer
string = str(42)
print(string) # "42"
print(type(string)) # <class 'str'>
# From float
string = str(3.14159)
print(string) # "3.14159"
# From boolean
string = str(True)
print(string) # "True"
# From complex number
string = str(3+4j)
print(string) # "(3+4j)"
# From list
string = str([1, 2, 3])
print(string) # "[1, 2, 3]"
# From dictionary
string = str({"name": "Alice", "age": 30})
print(string) # "{'name': 'Alice', 'age': 30}"
# From None
string = str(None)
print(string) # "None"
# Custom objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
person = Person("Alice", 30)
string = str(person)
print(string) # "Person(name=Alice, age=30)"
Converting to Boolean (bool())
The bool() function converts values to True or False according to their "truthiness" in Python:
# Falsy values convert to False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False (empty string)
print(bool([])) # False (empty list)
print(bool({})) # False (empty dictionary)
print(bool(())) # False (empty tuple)
print(bool(set())) # False (empty set)
print(bool(None)) # False
# Everything else converts to True
print(bool(1)) # True
print(bool(-1)) # True (any non-zero number)
print(bool(0.1)) # True (any non-zero float)
print(bool("hello")) # True (non-empty string)
print(bool([1, 2, 3])) # True (non-empty list)
print(bool({1, 2, 3})) # True (non-empty set)
Converting to Complex (complex())
# From integers/floats
complex_num = complex(3, 4) # 3 + 4j
print(complex_num)
# From a single number (imaginary part is 0)
complex_num = complex(5) # 5 + 0j
print(complex_num)
# From string
complex_num = complex("3+4j")
print(complex_num) # (3+4j)
# Error cases
try:
complex_num = complex("3+4i") # Will fail - Python uses j for imaginary unit
except ValueError as e:
print(f"Error: {e}") # Invalid complex string: '3+4i'
Converting Between Collection Types
Python provides built-in functions to convert between different collection types like lists, tuples, sets, and dictionaries.
Converting to List (list())
# From tuple
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # [1, 2, 3]
# From string (creates a list of characters)
my_string = "hello"
my_list = list(my_string)
print(my_list) # ['h', 'e', 'l', 'l', 'o']
# From set
my_set = {1, 2, 3, 3, 2, 1} # Duplicates are automatically removed in sets
my_list = list(my_set)
print(my_list) # [1, 2, 3] (order may vary)
# From dictionary (gets the keys)
my_dict = {"a": 1, "b": 2, "c": 3}
my_list = list(my_dict)
print(my_list) # ['a', 'b', 'c']
# From dictionary items, keys, or values
keys_list = list(my_dict.keys())
print(keys_list) # ['a', 'b', 'c']
values_list = list(my_dict.values())
print(values_list) # [1, 2, 3]
items_list = list(my_dict.items())
print(items_list) # [('a', 1), ('b', 2), ('c', 3)]
# From range
my_range = range(5)
my_list = list(my_range)
print(my_list) # [0, 1, 2, 3, 4]
Converting to Tuple (tuple())
# From list
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3)
# From string
my_string = "hello"
my_tuple = tuple(my_string)
print(my_tuple) # ('h', 'e', 'l', 'l', 'o')
# From set
my_set = {1, 2, 3}
my_tuple = tuple(my_set)
print(my_tuple) # (1, 2, 3) (order may vary)
# From dictionary
my_dict = {"a": 1, "b": 2, "c": 3}
my_tuple = tuple(my_dict)
print(my_tuple) # ('a', 'b', 'c')
# Immutable - attempts to modify will fail
try:
my_tuple[0] = 5 # This will raise an error
except TypeError as e:
print(f"Error: {e}") # Error: 'tuple' object does not support item assignment
Converting to Set (set())
# From list (removes duplicates)
my_list = [1, 2, 3, 1, 2, 3]
my_set = set(my_list)
print(my_set) # {1, 2, 3}
# From tuple
my_tuple = (1, 2, 3, 1, 2, 3)
my_set = set(my_tuple)
print(my_set) # {1, 2, 3}
# From string (set of unique characters)
my_string = "hello"
my_set = set(my_string)
print(my_set) # {'h', 'e', 'l', 'o'} (only one 'l' as duplicates are removed)
# From dictionary (gets keys)
my_dict = {"a": 1, "b": 2, "c": 3}
my_set = set(my_dict)
print(my_set) # {'a', 'b', 'c'}
Converting to Dictionary (dict())
# From sequence of key-value pairs
my_list = [("a", 1), ("b", 2), ("c", 3)]
my_dict = dict(my_list)
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
my_tuple = (("a", 1), ("b", 2), ("c", 3))
my_dict = dict(my_tuple)
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
# Using keyword arguments
my_dict = dict(a=1, b=2, c=3)
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
# From two sequences using zip
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
# Error cases
try:
# List without proper key-value pairs
my_dict = dict([1, 2, 3])
except TypeError as e:
print(f"Error: {e}") # cannot convert dictionary update sequence element #0 to a sequence
Specialized Type Conversions
Working with Binary, Octal, and Hexadecimal
# Integer to binary string
binary_str = bin(42)
print(binary_str) # '0b101010'
# Remove prefix
binary_str_no_prefix = bin(42)[2:]
print(binary_str_no_prefix) # '101010'
# Integer to octal string
octal_str = oct(42)
print(octal_str) # '0o52'
# Remove prefix
octal_str_no_prefix = oct(42)[2:]
print(octal_str_no_prefix) # '52'
# Integer to hexadecimal string
hex_str = hex(42)
print(hex_str) # '0x2a'
# Remove prefix
hex_str_no_prefix = hex(42)[2:]
print(hex_str_no_prefix) # '2a'
# Converting back to integers
binary_int = int('101010', 2)
print(binary_int) # 42
octal_int = int('52', 8)
print(octal_int) # 42
hex_int = int('2a', 16)
print(hex_int) # 42
# Format integers with different bases
print(format(42, 'b')) # '101010' (binary)
print(format(42, 'o')) # '52' (octal)
print(format(42, 'x')) # '2a' (hex lowercase)
print(format(42, 'X')) # '2A' (hex uppercase)
# Format with padding
print(format(42, '08b')) # '00101010' (8-digit binary with zero padding)
print(format(42, '#x')) # '0x2a' (with prefix)
Conversion with Decimal and Fraction
For precise decimal arithmetic or working with rational numbers:
from decimal import Decimal
from fractions import Fraction
# Converting to Decimal
dec_from_int = Decimal(5)
print(dec_from_int) # 5
dec_from_float = Decimal(3.14) # May not be exact due to float representation
print(dec_from_float) # 3.140000000000000124344978758017532527446746826171875
# Better to create from string for exact representation
dec_from_string = Decimal('3.14')
print(dec_from_string) # 3.14
# Converting to Fraction
frac_from_int = Fraction(5)
print(frac_from_int) # 5/1
frac_from_float = Fraction(3.14)
print(frac_from_float) # 157/50
frac_from_string = Fraction('3.14')
print(frac_from_string) # 157/50
frac_from_decimal = Fraction(Decimal('3.14'))
print(frac_from_decimal) # 157/50
# Create from numerator and denominator
frac_direct = Fraction(1, 3)
print(frac_direct) # 1/3
# Converting back to float
float_from_decimal = float(Decimal('3.14'))
print(float_from_decimal) # 3.14
float_from_fraction = float(Fraction(1, 3))
print(float_from_fraction) # 0.3333333333333333
Date and Time Conversions
from datetime import datetime, date
# String to datetime
date_string = "2025-04-15 14:30:15"
date_obj = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(date_obj) # 2025-04-15 14:30:15
# Datetime to string
formatted_date = date_obj.strftime("%B %d, %Y, %I:%M %p")
print(formatted_date) # "April 15, 2025, 02:30 PM"
# Timestamp (seconds since epoch) to datetime
timestamp = 1712345678 # Example timestamp
date_from_timestamp = datetime.fromtimestamp(timestamp)
print(date_from_timestamp) # 2024-04-06 19:27:58
# Datetime to timestamp
timestamp_from_date = date_obj.timestamp()
print(timestamp_from_date) # 1744789815.0
# Date to datetime
today = date.today()
datetime_from_date = datetime.combine(today, datetime.min.time())
print(datetime_from_date) # 2025-04-17 00:00:00
Bytes and String Conversions
# String to bytes
text = "Hello, World!"
bytes_data = text.encode('utf-8')
print(bytes_data) # b'Hello, World!'
# Bytes to string
text_from_bytes = bytes_data.decode('utf-8')
print(text_from_bytes) # "Hello, World!"
# Specify encoding
text = "こんにちは" # Japanese "Hello"
bytes_data = text.encode('utf-8')
print(bytes_data) # b'\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf'
# Error handling
try:
bytes_data = text.encode('ascii') # ASCII can't represent Japanese
except UnicodeEncodeError as e:
print(f"Error: {e}") # 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
# With error handling strategy
bytes_data = text.encode('ascii', errors='ignore')
print(bytes_data) # b'' (all characters were ignored)
bytes_data = text.encode('ascii', errors='replace')
print(bytes_data) # b'?????' (replaced with ? marks)
Converting User Input
A common use case for type conversion is handling user input, which is always received as strings:
# Basic input handling
def get_integer_input(prompt):
"""
Get an integer input from the user, with validation.
"""
while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("Please enter a valid integer.")
def get_float_input(prompt):
"""
Get a float input from the user, with validation.
"""
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("Please enter a valid number.")
def get_yes_no_input(prompt):
"""
Get a yes/no input from the user.
"""
while True:
response = input(prompt).strip().lower()
if response in ('yes', 'y'):
return True
elif response in ('no', 'n'):
return False
else:
print("Please enter 'yes' or 'no'.")
# Example usage
# age = get_integer_input("Enter your age: ")
# height = get_float_input("Enter your height in meters: ")
# likes_python = get_yes_no_input("Do you like Python? (yes/no): ")
#
# print(f"Age: {age} (type: {type(age)})")
# print(f"Height: {height} (type: {type(height)})")
# print(f"Likes Python: {likes_python} (type: {type(likes_python)})")
Handling Multiple Input Types
def parse_input(value):
"""
Attempt to parse input as the most appropriate type.
"""
# First, try to convert to an integer
try:
return int(value)
except ValueError:
pass
# Next, try to convert to a float
try:
return float(value)
except ValueError:
pass
# Check for boolean values
if value.lower() in ('true', 'yes', 'y', 't'):
return True
if value.lower() in ('false', 'no', 'n', 'f'):
return False
# If nothing else worked, return as string
return value
# Example usage
inputs = ["42", "3.14", "true", "hello", "123.45abc"]
for input_value in inputs:
parsed = parse_input(input_value)
print(f"Original: '{input_value}', Parsed: {parsed}, Type: {type(parsed)}")
# Output:
# Original: '42', Parsed: 42, Type:
# Original: '3.14', Parsed: 3.14, Type:
# Original: 'true', Parsed: True, Type:
# Original: 'hello', Parsed: hello, Type:
# Original: '123.45abc', Parsed: 123.45abc, Type:
Best Practices for Type Conversion
Handling Conversion Errors
Always use try/except blocks when converting user input or unpredictable data:
def safe_convert_to_int(value):
"""
Safely convert a value to an integer.
Returns the converted value or None if conversion fails.
"""
try:
return int(value)
except (ValueError, TypeError) as e:
print(f"Could not convert '{value}' to an integer: {e}")
return None
# Examples
print(safe_convert_to_int("42")) # 42
print(safe_convert_to_int("hello")) # None (with error message)
print(safe_convert_to_int(None)) # None (with error message)
Type Checking Before Conversion
Use type checking to avoid unnecessary conversions:
def ensure_int(value):
"""
Ensure a value is an integer, converting if necessary.
"""
if isinstance(value, int):
return value
try:
return int(value)
except (ValueError, TypeError):
raise ValueError(f"Could not convert {value} to an integer")
# Examples
print(ensure_int(42)) # Already an int, returns 42
print(ensure_int("42")) # Converts to 42
try:
print(ensure_int("hello"))
except ValueError as e:
print(f"Error: {e}") # Error: Could not convert hello to an integer
Avoiding Common Pitfalls
# Pitfall 1: Rounding vs. Truncation
num = 3.7
int_num = int(num) # 3 (truncates, doesn't round)
rounded = round(num) # 4 (rounds properly)
print(f"Truncated: {int_num}, Rounded: {rounded}")
# Pitfall 2: Floating-point precision
result = int(0.1 + 0.2) # Expected 0.3, but actually 0.30000000000000004
print(result) # 0 (truncated from slightly over 0.3)
# Better approach
from decimal import Decimal
result = int(Decimal('0.1') + Decimal('0.2'))
print(result) # 0
# Pitfall 3: Assuming all strings can be converted
values = ["42", "3.14", "hello", ""]
for val in values:
try:
print(int(val))
except ValueError as e:
print(f"Cannot convert '{val}': {e}")
# Pitfall 4: Losing data in conversions
float_val = 3.99
int_val = int(float_val)
print(f"Original: {float_val}, Converted: {int_val}") # Original: 3.99, Converted: 3 (decimal part lost)
# Pitfall 5: Character vs. ASCII value conversion
char = 'A'
ascii_val = ord(char) # Get ASCII value
print(f"Character: {char}, ASCII: {ascii_val}") # Character: A, ASCII: 65
back_to_char = chr(ascii_val) # Convert back to character
print(f"ASCII: {ascii_val}, Character: {back_to_char}") # ASCII: 65, Character: A
Practical Applications
CSV Data Processing
import csv
def process_csv_data(filename):
"""
Read a CSV file and convert data to appropriate types.
"""
data = []
with open(filename, 'r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
# Convert string values to appropriate types
processed_row = {}
for key, value in row.items():
# Skip empty values
if value == '':
processed_row[key] = None
continue
# Try to convert to appropriate type
try:
# Try integer conversion first
processed_row[key] = int(value)
except ValueError:
try:
# Try float conversion
processed_row[key] = float(value)
except ValueError:
# Handle boolean values
if value.lower() in ('true', 'yes', 'y'):
processed_row[key] = True
elif value.lower() in ('false', 'no', 'n'):
processed_row[key] = False
else:
# Keep as string if no conversion works
processed_row[key] = value
data.append(processed_row)
return data
# Example of how this would be used (uncomment to test with a real CSV file)
# csv_data = process_csv_data('data.csv')
# for row in csv_data:
# print(row)
Temperature Converter
def temperature_converter():
"""
Simple temperature converter between Celsius and Fahrenheit.
"""
print("Temperature Converter")
print("=====================")
while True:
temp_str = input("Enter temperature (e.g., '32F', '0C'): ")
if not temp_str:
break
try:
# Extract the numerical value and unit
if temp_str[-1].upper() in ('C', 'F'):
value = float(temp_str[:-1])
unit = temp_str[-1].upper()
else:
# Assume Celsius if no unit is provided
value = float(temp_str)
unit = 'C'
# Convert between units
if unit == 'C':
fahrenheit = (value * 9/5) + 32
print(f"{value}°C = {fahrenheit:.1f}°F")
else:
celsius = (value - 32) * 5/9
print(f"{value}°F = {celsius:.1f}°C")
except ValueError:
print("Invalid temperature format. Please use formats like '32F' or '0C'.")
print() # Empty line for readability
print("Goodbye!")
# Uncomment to run the temperature converter
# temperature_converter()
Custom Type Conversion for Objects
class Point:
"""A 2D point class with x and y coordinates."""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
# Convert Point to tuple
def to_tuple(self):
return (self.x, self.y)
# Convert Point to dict
def to_dict(self):
return {"x": self.x, "y": self.y}
# Static method to create Point from tuple
@staticmethod
def from_tuple(t):
return Point(t[0], t[1])
# Static method to create Point from dict
@staticmethod
def from_dict(d):
return Point(d["x"], d["y"])
# Static method to create Point from string
@staticmethod
def from_string(s):
# Expected format: "Point(x, y)" or "(x, y)"
s = s.strip()
if s.startswith("Point("):
s = s[6:-1] # Remove "Point(" and ")"
elif s.startswith("(") and s.endswith(")"):
s = s[1:-1] # Remove "(" and ")"
# Split by comma and convert to floats
parts = s.split(",")
if len(parts) != 2:
raise ValueError("String must contain exactly two values")
try:
x = float(parts[0].strip())
y = float(parts[1].strip())
return Point(x, y)
except ValueError:
raise ValueError("Could not convert string coordinates to float")
# Examples
p1 = Point(3, 4)
print(p1) # Point(3, 4)
# Convert to other types
tuple_version = p1.to_tuple()
print(tuple_version) # (3, 4)
dict_version = p1.to_dict()
print(dict_version) # {'x': 3, 'y': 4}
# Convert from other types back to Point
p2 = Point.from_tuple((5, 6))
print(p2) # Point(5, 6)
p3 = Point.from_dict({"x": 7, "y": 8})
print(p3) # Point(7, 8)
p4 = Point.from_string("Point(9, 10)")
print(p4) # Point(9.0, 10.0)
p5 = Point.from_string("(11, 12)")
print(p5) # Point(11.0, 12.0)
Practice Exercises
Exercise 1: Type Converter Tool
Create a function that takes a value and a target type name (e.g., "int", "float", "str", "bool", "list") and attempts to convert the value to that type. Handle exceptions appropriately.
Exercise 2: CSV Data Analyzer
Write a program that reads a CSV file, automatically detects and converts data types for each column, and provides basic statistics (min, max, average) for numeric columns.
Exercise 3: User Input Form
Create a form-like program that asks users for various pieces of information (name, age, height, etc.), converts inputs to appropriate types with validation, and then displays a summary.
Exercise 4: Number Base Converter
Write a function that converts a number between different bases (binary, octal, decimal, hexadecimal). The function should take a string representation of a number, its current base, and the target base.
Exercise 5: JSON Data Processor
Create a function that reads a JSON file, processes its contents by converting appropriate string values to numbers, booleans, or other types, and then saves the processed data back to a new JSON file.
Wrapping Up and Next Steps
Today we've explored the world of Python type conversion, from basic casting between numeric types to advanced conversions between complex data structures. Understanding type conversion is essential for handling data effectively and writing robust Python programs.
Key Takeaways
- Python handles some type conversions automatically (implicit conversion), but many require explicit conversion
- Built-in functions like int(), float(), str(), bool(), list() provide convenient ways to convert between types
- Always handle potential errors when converting types, especially when working with user input
- Different collection types (lists, tuples, sets, etc.) can be easily converted between each other
- Specialized conversions are available for working with different number bases, dates, and binary data
Where to Go from Here
- Explore how databases handle type conversions when storing and retrieving data
- Learn about serialization formats like JSON, YAML, and XML, and how they manage type information
- Dive deeper into high-precision numerical computing with Decimal and Fraction
- Experiment with custom type conversion by implementing __int__(), __float__(), __str__(), and other special methods in your classes
- Study type annotations and the typing module for adding type hints to your Python code
Additional Resources
- Python Built-in Functions Documentation
- Python Standard Types Documentation
- Python Decimal Module Documentation
- Python Fractions Module Documentation
- Python Type Hints (typing module) Documentation
In our next session, we'll explore conditional statements and loops in Python, building on our understanding of data types and operations to create more dynamic and responsive programs.