Lesson 09: Type Conversion (Changing Data Types)
Learn Python type conversion for BIM automation: fix text vs number errors, format labels, handle Excel data, and make scripts work correctly.
Introduction
You've already run into this problem.
You want to print "Level 3" but you have the number 3 stored in a variable. You try to combine them and Python throws an error.
Or you read area values from an Excel export. They look like numbers, but Python treats them as text. Your calculations fail.
This happens because Python is strict about data types. A number is not text. Text is not a number. You can't mix them without being explicit.
Type conversion is how you change data from one type to another. It's a practical necessity, not a theoretical concept.
This lesson shows you when you need type conversion and how to do it correctly.
Lesson Overview
This section contains a general overview of topics you will learn in this lesson.
- Understand why type conversion is necessary
- Convert numbers to strings (and back)
- Convert between integers and floats
- Convert to booleans
- Handle conversion errors
- Apply type conversion to real architectural workflows
Why Type Conversion Matters
Python won't let you mix types without permission.
floor = 3
message = "Level " + floor
# Error: TypeError: can only concatenate str (not "int") to str
You need to explicitly convert the number to a string:
floor = 3
message = "Level " + str(floor)
print(message) # Output: Level 3
This explicitness prevents bugs. Python forces you to be clear about your intentions.
Checking a Variable's Type
Use type() to see what type a variable is.
floor_count = 12
floor_height = 3.2
project_name = "Community Center"
is_issued = True
print(type(floor_count)) # Output: <class 'int'>
print(type(floor_height)) # Output: <class 'float'>
print(type(project_name)) # Output: <class 'str'>
print(type(is_issued)) # Output: <class 'bool'>
Converting to String: str()
Convert any type to a string using str().
Number to String
floor = 3
floor_str = str(floor)
print(floor) # Output: 3 (integer)
print(floor_str) # Output: 3 (string)
print(type(floor_str)) # Output: <class 'str'>
Why This Matters: File Naming
project_code = "2024-001"
revision = 3
# Wrong (can't concatenate string and int)
file_name = project_code + "_R" + revision + ".pdf"
# Error: TypeError
# Correct
file_name = project_code + "_R" + str(revision) + ".pdf"
print(file_name) # Output: 2024-001_R3.pdf
Float to String
area = 450.75
area_str = str(area)
print(area_str) # Output: 450.75
print(type(area_str)) # Output: <class 'str'>
Boolean to String
is_issued = True
status_str = str(is_issued)
print(status_str) # Output: True
print(type(status_str)) # Output: <class 'str'>
Converting to Integer: int()
Convert strings or floats to integers using int().
String to Integer
floor_str = "12"
floor_int = int(floor_str)
print(floor_int) # Output: 12
print(type(floor_int)) # Output: <class 'int'>
# Now you can do math
total = floor_int + 3
print(total) # Output: 15
Float to Integer (Truncates Decimal)
area = 450.89
area_int = int(area)
print(area_int) # Output: 450 (decimal is cut off, not rounded)
Important: int() truncates (cuts off) the decimal. It doesn't round.
height = 3.9
height_int = int(height)
print(height_int) # Output: 3 (not 4)
Architectural Example: Counting Full Floors
building_height = 32.7
floor_height = 3.2
# How many full floors fit?
full_floors = int(building_height / floor_height)
print(full_floors) # Output: 10
# More precise
full_floors = int(building_height // floor_height)
print(full_floors) # Output: 10
Converting to Float: float()
Convert strings or integers to floats using float().
String to Float
area_str = "450.75"
area_float = float(area_str)
print(area_float) # Output: 450.75
print(type(area_float)) # Output: <class 'float'>
# Now you can calculate
total_area = area_float * 2
print(total_area) # Output: 901.5
Integer to Float
floor_count = 12
floor_count_float = float(floor_count)
print(floor_count_float) # Output: 12.0
print(type(floor_count_float)) # Output: <class 'float'>
Why This Matters: Data from External Sources
# Data imported from Excel or CSV comes as strings
areas_from_excel = ["450.5", "380.2", "520.8"]
# Convert to floats for calculations
areas = []
for area_str in areas_from_excel:
area = float(area_str)
areas.append(area)
total_area = sum(areas)
print(total_area) # Output: 1351.5
Converting to Boolean: bool()
Convert other types to boolean using bool().
How It Works
Python converts values to True or False based on whether they're "truthy" or "falsy".
Falsy values (become False):
0(zero)0.0(zero float)""(empty string)None
Truthy values (become True):
- Any non-zero number
- Any non-empty string
print(bool(1)) # Output: True
print(bool(0)) # Output: False
print(bool(42)) # Output: True
print(bool(-5)) # Output: True
print(bool("text")) # Output: True
print(bool("")) # Output: False
print(bool(3.14)) # Output: True
print(bool(0.0)) # Output: False
Architectural Example: Checking for Empty Values
room_name = ""
area = 0
status = "Draft"
has_name = bool(room_name)
has_area = bool(area)
has_status = bool(status)
print(has_name) # Output: False (empty string)
print(has_area) # Output: False (zero)
print(has_status) # Output: True (non-empty string)
Conversion Errors
Not all conversions are possible. Python will raise an error if you try to convert something that doesn't make sense.
Invalid String to Integer
text = "hello"
number = int(text)
# Error: ValueError: invalid literal for int() with base 10: 'hello'
You can only convert strings that look like numbers.
# These work
int("123") # Output: 123
int("0") # Output: 0
int("-45") # Output: -45
# These don't
int("12.5") # Error: ValueError (use float() first)
int("hello") # Error: ValueError
int("12a") # Error: ValueError
Invalid String to Float
text = "Room 101"
area = float(text)
# Error: ValueError: could not convert string to float: 'Room 101'
# These work
float("12.5") # Output: 12.5
float("0.0") # Output: 0.0
float("123") # Output: 123.0
# These don't
float("hello") # Error: ValueError
float("12.5m") # Error: ValueError (can't have letters)
The Pain vs The Python Fix
The Pain: Reading room areas from an Excel export. They're stored as text. Your area calculations fail. You manually convert 200 values.
The Python Fix: Convert once, calculate reliably.
# Areas imported from Excel (as strings)
area_data = ["450.5", "380.2", "520.8", "410.3", "395.7"]
# Convert all to floats
areas = []
for area_str in area_data:
area = float(area_str)
areas.append(area)
# Now calculate
total_area = sum(areas)
average_area = total_area / len(areas)
print(f"Total area: {total_area} m²")
print(f"Average area: {average_area} m²")
# Output:
# Total area: 2157.5 m²
# Average area: 431.5 m²
Real Architectural Workflows
Example 1: Building File Names with Number
project_code = "2024-001"
discipline = "Architecture"
sheet_number = 101
revision = 3
# Convert numbers to strings for file name
file_name = f"{project_code}_{discipline}_Sheet_{sheet_number}_R{str(revision).zfill(2)}.pdf"
print(file_name)
# Output: 2024-001_Architecture_Sheet_101_R03.pdf
Note: .zfill(2) pads with zeros (we'll learn string methods in depth later).
Example 2: Processing User Input
# User enters floor count as text
floor_input = "12"
# Convert to integer for calculations
floor_count = int(floor_input)
floor_height = 3.2
total_height = floor_count * floor_height
print(f"Total height: {total_height}m")
# Output: Total height: 38.4m
Example 3: Rounding Areas for Display
# Precise area from calculation
room_area = 450.7893
# Convert to int to round down
area_rounded = int(room_area)
print(f"Area: {area_rounded} m²")
# Output: Area: 450 m²
If you want proper rounding (not truncating), use round():
room_area = 450.7893
area_rounded = round(room_area)
print(area_rounded) # Output: 451
f-strings: An Alternative to Conversion
Earlier, we converted numbers to strings for concatenation:
floor = 3
message = "Level " + str(floor)
With f-strings, Python handles conversion automatically:
floor = 3
message = f"Level {floor}"
print(message) # Output: Level 3
This is cleaner and more readable.
Architectural Example
project = "Community Center"
floor_count = 12
area = 3500.5
is_approved = True
report = f"Project: {project}, Floors: {floor_count}, Area: {area}m², Approved: {is_approved}"
print(report)
# Output: Project: Community Center, Floors: 12, Area: 3500.5m², Approved: True
Type Conversion Chain
Sometimes you need to convert through multiple types.
# String that looks like a float, but you want an integer
area_str = "450.75"
# Can't go directly string → int
area_int = int(area_str)
# Error: ValueError: invalid literal for int() with base 10: '450.75'
# Convert string → float → int
area_float = float(area_str)
area_int = int(area_float)
print(area_int) # Output: 450
# Or in one line
area_int = int(float(area_str))
print(area_int) # Output: 450
Common Mistakes
Mistake 1: Converting strings with units
area = "450 m²"
area_float = float(area)
# Error: ValueError (can't convert because of " m²")
Fix: Remove the unit first.
area = "450 m²"
area_clean = area.replace(" m²", "")
area_float = float(area_clean)
print(area_float) # Output: 450.0
Mistake 2: Expecting int() to round
height = 3.9
height_int = int(height)
print(height_int) # Output: 3 (not 4!)
Use round() if you want rounding:
height = 3.9
height_rounded = round(height)
print(height_rounded) # Output: 4
Mistake 3: Not checking if conversion is possible
user_input = "abc"
number = int(user_input)
# Error: ValueError
You'll learn error handling in a later module, but for now, be aware conversions can fail.
Mistake 4: Converting empty strings
area_str = ""
area_float = float(area_str)
# Error: ValueError: could not convert string to float: ''
Check for empty values first:
area_str = ""
if area_str:
area_float = float(area_str)
else:
area_float = 0.0
print(area_float) # Output: 0.0
Assignme
- Create a new file called
type_conversion_practice.py - File name builder:
- Variables: project = "2024-001", sheet = 101, revision = 3
- Build: "2024-001_Sheet_101_R03.pdf"
- Convert numbers to strings
- Print the file name
- Area calculations from string data:
- Start with: areas = ["450.5", "380.2", "520.8"]
- Convert each to float
- Calculate total area
- Calculate average area
- Print results
- Floor count calculator:
- Variables: building_height = 35.7, floor_height = 3.2
- Calculate how many full floors fit (use int())
- Calculate leftover height
- Print both values
- Room status checker:
- Variables: room_name = "", area = 0, status = "Draft"
- Use bool() to check which values are "truthy"
- Print results for each
- String to number with error:
- Try: area_str = "450 m²"
- Try to convert directly to float (see the error)
- Clean the string first (remove " m²")
- Then convert to float
- Print result
- Experiment:
- Try converting "hello" to int (see the error)
- Try converting 3.9 to int (does it round?)
- Try converting an empty string to float (see the error)
- Use f-strings to avoid manual conversion for "Level 5"
Knowledge Check
The following questions are an opportunity to reflect on key topics in this lesson.
- Why can't you concatenate a string and an integer directly?
- How do you convert a number to a string?
- What happens to the decimal when you convert a float to an int?
- How do you convert a string like "450.5" to a float?
- What does bool(0) return?
- What does bool("") return?
- Can you convert the string "hello" to an integer?
- How do f-strings help with type conversion?
- How do you convert "450.75" to an integer?
Additional Resources
This section contains helpful links to related content. It isn't required, so consider it supplemental.
- Python's official documentation on type conversion covers built-in conversion functions
- Real Python's guide to type conversion explains conversion with detailed examples
- Python's round() function for proper rounding instead of truncating