Skip to content

Mastering Python's Core Data Types: Hands-On Exercises and Tutorials

Updated: at 12:48 PM

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:

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:

Complex Numbers

Complex numbers have real and imaginary parts.

c1 = 2 + 3j
print(c1.real) # 2.0
print(c1.imag) # 3.0

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:

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:

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:

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:

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))

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:

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:

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:

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

Tuples

Tuples are immutable ordered sequences in Python.

point = (10, 20)
x, y = point # Unpack tuple

print(x) # 10

Properties of tuples:

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:

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:

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:

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:

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:

With fluency in Python’s core data representations, programmers can effectively tackle a wide range of programming problems.

References