Chapter 3: Python Data Types – Numbers, Strings, Lists, Tuples, Dictionaries, Sets

1. Numbers (int, float, complex)

Definition: Python supports three numeric types:

  • int - Whole numbers (5, -10)
  • float - Decimals (3.14, -0.5)
  • complex - a + bj form (2 + 3j)
num1 = 10          # int  
num2 = 3.14        # float  
num3 = 2 + 5j      # complex  

print(type(num1))  # <class 'int'>
print(num3.real)   # 2.0 (real part)
<class 'int'>
2.0

Exercise 1:

  1. Create an integer, float, and complex number
  2. Print their types
  3. Multiply the integer and float
a = 5            # int
b = 3.14         # float
c = 1 + 2j       # complex
print(type(a), type(b), type(c))
print(a * b)     # 15.7

2. Strings (str)

Definition: Text data enclosed in '' or "" (immutable).

String Operations

name = "Python"
greeting = 'Hello, "World"!'

# Indexing
print(name[0])    # 'P'

# Methods
print(name.upper())  # 'PYTHON'
print(" hello ".strip())  # 'hello'

Output

P
PYTHON
hello

Exercise 2:

  1. Create s = "Programming"
  2. Print its 4th character and length
  3. Replace all "m" with "M"
s = "Programming"
print(s[3], len(s))       # 'g' 11
print(s.replace("m", "M")) # 'PrograMMing'

3. Data Structures

Lists

Ordered, mutable collection

fruits = ["apple", "banana"]
fruits.append("cherry")

Tuples

Ordered, immutable

colors = ("red", "green")
print(colors[0])  # 'red'

Dictionaries

Key-value pairs

person = {"name": "Alice", "age": 25}

Sets

Unique, unordered items

unique_nums = {1, 2, 2, 3}  # {1, 2, 3}

Exercise 3:

Create a dictionary of 3 countries with their capitals, then:

  1. Add a new country
  2. Print all keys
  3. Check if "France" exists
countries = {"USA": "Washington", "India": "Delhi"}
countries["Japan"] = "Tokyo"
print(countries.keys())
print("France" in countries)  # False

Summary Table

Type Example Mutable? Duplicates?
list [1, 2, 3]
tuple (1, 2)
dict {"key": "value"} Keys: ❌
set {1, 2, 3}