Understanding data types is fundamental to programming in Python. This guide provides hands-on coding exercises to help reinforce your knowledge of Python’s basic data structures like numbers, strings, lists, dictionaries etc. Working through concrete examples can deepen comprehension and retention of key programming concepts.
Table of Contents
Open Table of Contents
Prerequisites
The exercises assume basic Python syntax knowledge and experience running scripts. For Python beginners, an introductory tutorial is recommended first.
Numeric Types
Python provides various numeric data types including integers, floats, complex numbers etc. Let’s explore some exercises for numeric types.
Integers
Integers represent whole numbers. Let’s try some integer arithmetic:
print(100 + 200) # 300
print(10 / 3) # 3, truncated integer division
Key points about integer arithmetic:
- Operations between integers return integers
- Division truncates fractional part
- Exponentiation raises to power
Floating-Point Numbers
Floats represent real numbers with fractional precision:
print(10.0 / 3) # 3.3333333333333335
print(2.5 ** 3) # 15.625
Observations about floats:
- Division produces fractional results
- Supports exponentiation
- Mixed types lead to float outputs
Complex Numbers
Complex numbers have real and imaginary parts.
c1 = 2 + 3j
print(c1.real) # 2.0
print(c1.imag) # 3.0
- Imaginary unit represented by
j
- Access real and imaginary parts via attributes
- Support arithmetic operations
Exercise 1: Type Conversions and Mixed Operands
Let’s illustrate type conversions and mixed arithmetic:
x = 100 # int
print(float(x)) # 100.0
print(str(x)) # '100'
print(complex(x)) # (100+0j)
y = 3.14 # float
print(int(y)) # 3
z = 2 + 1j # complex
print(int(z)) # TypeError
print(x + y) # 103.14, mixed int and float
This demonstrates:
- Type conversions between numeric types
- Arithmetic with mixed operand types
Exercise 2: Testing Numeric Limits
Let’s test the limits of numeric types:
import sys
print(sys.maxsize) # Max int value before overflow
print(2**1024) # Float max exponent before infinity
c = 1000 + 1000j
print(c) # (1000+1000j)
c = 1000000000000 + 1000000000000j # Formats as exponential
print(c) # (1e+12+1e+12j)
Key takeaways:
- Integers have maximum range before overflow
- Floats can represent very large/small numbers
- Complex format changes at magnitudes
This reveals precision and range limits of numeric types.
Booleans
Booleans represent truth values True and False in Python.
print(5 > 2) # True
x = True
y = False
print(x and y) # Logical AND
print(x or y) # Logical OR
Some exercises to apply Boolean operations:
Exercise 3: Short-Circuit Evaluation
Short-circuit evaluation prevents unnecessary code execution:
# With short-circuiting no exception raised
print(False and raise Exception())
print(True or raise Exception())
# Without short-circuiting exception raised
print(False & raise Exception())
print(True | raise Exception())
This demonstrates short-circuiting behavior in Boolean expressions.
Exercise 4: Truth Value Testing
Different objects have inherent truth values:
print(bool(0)) # False
print(bool("hello")) # True
class MyClass:
def __init__(self):
self.att = "Hello"
def __len__(self):
return 0
obj = MyClass()
print(bool(obj)) # False, __len__ is 0
This shows how truth testing works in Python:
- Numbers: Zero is False, non-zero is True
- Strings: Empty is False, non-empty is True
- Custom classes use
__bool__
or__len__
Strings
Strings represent textual data in Python. Some key operations:
s = "Hello"
print(s[0]) # 'H'
s2 = "World"
print(s + " " + s2) # 'Hello World'
print(s.upper()) # 'HELLO'
Properties of Python strings:
- Immutable sequenced type
- Support indexing, slicing, methods
- Useful for text processing
Some exercises to apply strings:
Exercise 5: Formatted Printing
Formatted printing injects values into strings:
name = "Eric"
age = 25
print(f"Name: {name}, Age: {age}")
print("My name is {}, I am {} years old".format(name, age))
- f-strings provide concise formatted strings
- str.format() method offers flexible substitutions
Exercise 6: Input Parsing and Validation
We can validate formatted string input:
import re
phone = input("Phone number: ")
if not re.match(r"\d{10}", phone):
print("Invalid phone format")
email = input("Email: ")
if not re.match(r"\w+@\w+\.com", email):
print("Invalid email")
This shows string validation:
- Regular expressions match text patterns
- Can sanitize free-form string input
Lists
Lists represent ordered, mutable sequences in Python.
nums = [1, 2, 3]
nums.append(4)
for n in nums:
print(n) # Prints 1, 2, 3, 4
Key characteristics of Python lists:
- Ordered collections allowing duplicates
- Mutable sequences, can modify in-place
- Flexible for data wrangling tasks
Some hands-on list exercises:
Exercise 7: List Comprehensions
List comprehensions provide a concise syntax for list operations:
squares = [x**2 for x in range(10)]
even_nums = [i for i in range(30) if i % 2 == 0]
List comprehensions allow:
- Transforming and filtering lists
- Generating lists from scratch
- More efficient than for loops
Exercise 8: Multidimensional Lists
Lists can represent multidimensional structures:
grid = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(grid[1][2]) # 6, nested index
cube = [[[1, 2], [3, 4]],
[[5, 6], [7, 8]]]
print(cube[0][1][0]) # 3, 3D index
- Lists can be nested to arbitrary depth
- Useful for matrices, cubes etc.
Tuples
Tuples are immutable ordered sequences in Python.
point = (10, 20)
x, y = point # Unpack tuple
print(x) # 10
Properties of tuples:
- Immutable sequences, cannot modify after creation
- Support indexing, slicing, iteration like lists
- Useful for fixed data
Exercise 9: Swapping Values
Tuple unpacking provides an easy way to swap values:
x, y = 10, 20
print(x, y) # 10, 20
x, y = y, x # Swap
print(x, y) # 20, 10
Sets
Sets represent unordered collections of unique elements in Python.
numbers = {1, 2, 3}
numbers.add(4)
print(3 in numbers) # Membership test
Key set properties:
- Unordered collection of distinct elements
- Support unions, intersections, diffs
- Efficient membership testing
Exercise 10: Set Operations
We can perform set operations like:
set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
print(set1.union(set2))
print(set1.intersection(set2))
print(set1.difference(set2))
# More complex set logic
set3 = {1, 3, 5, 7, 9}
print(set1.union(set2).difference(set3))
This demonstrates:
- Unions, intersections, differences
- Chaining multiple set operations
Dictionaries
Dictionaries map keys to values in Python.
ages = {"Alice": 25, "Bob": 27}
print(ages["Alice"]) # 25
ages["Charlie"] = 30 # Insert
for name in ages:
print(name, ages[name]) # Iteration
Key dictionary properties:
- Unordered mappings of key-value pairs
- Keys must be immutable types
- Efficient lookup by key
- Nesting provides flexibility
Exercise 11: Group By
We can group data in a dictionary:
categories = ["Zero", "One", "Two"]
nums = [1, 2, 3, 4, 5, 6]
grouped = {}
for n in nums:
mod = n % 3
if mod not in grouped:
grouped[mod] = []
grouped[mod].append(n)
print(grouped)
# {0: [3, 6], 1: [1, 4], 2: [2, 5]}
This demonstrates:
- Creating a grouping based on keys
- Appending values to nested list
- Useful for aggregation scenarios
Summary
Mastering Python’s core data types provides a solid foundation for programmatically working with real-world data. This guide covered practical hands-on exercises focused on numbers, strings, lists, tuples, sets and dictionaries to help reinforce key concepts through concrete examples and live coding.
Some suggestions for extending your learning:
- Apply data types to math, science, game, web development projects
- Process different file formats like CSV, JSON, HTML using Python types
- Develop classes encapsulating multiple data structures
- Utilize Python’s extensive modules for specialized data types
With fluency in Python’s core data representations, programmers can effectively tackle a wide range of programming problems.