← Back to Hub
Module 2 Week 7 • Explicit Type Conversion

Type Casting

Convert variables manually between types using int(), float(), and str() conversion functions.

1. What is Type Casting?

Sometimes you need to convert a variable from one data type to another. This manual conversion is called **Type Casting** (or explicit type conversion). Python uses these built-in constructor functions:

  • int(): Converts value to an integer. It truncates (chops off) decimals of floats (e.g., int(3.9) becomes 3).
  • float(): Converts value to a decimal float (e.g., float("5") becomes 5.0).
  • str(): Converts value to a text string (e.g., str(45) becomes "45").

2. When Casting Fails

If you try to convert a string that doesn't look like a number (like int("apple")), Python will throw a ValueError and crash the program. Always make sure the text matches the numeric structure before casting!

💻 Python Code Examples

Example 1: Casting Floats to Integers

val1 = int(2.8) # Truncates to 2
val2 = int(-5.9) # Truncates to -5
print(val1, val2)

Description: int() chops off fractional parts without rounding numbers.

Example 2: Casting Strings to Integers

num_str = "100"
num = int(num_str)
print(num + 5) # Output: 105

Description: Converts string characters into numbers to enable calculations.

Example 3: Casting Numbers to Strings

age = 22
msg = "Age is " + str(age)
print(msg)

Description: Converts an integer to a string to join it with other text safely.

Example 4: Casting Strings to Floats

f_str = "3.14"
val = float(f_str)
print(val * 2)

Description: Converts decimal string text to a mathematical float variable.

Example 5: Integer to Float Conversion

num = float(10)
print(num) # Output: 10.0

Description: Converts an integer to float, adding a .0 decimal part.

Example 6: Casting Error Case

try:
    int("hello")
except ValueError as e:
    print("ValueError caught!")

Description: Casting alphabetic characters to integers raises a ValueError.

🧠 Active Retrieval Quizzes

Answer the following 10 multiple-choice questions to test your storage strength.

Question 1: What is type casting in Python?

Explanation: Type casting refers to manually converting values from one data type to another.

Question 2: What is the result of casting float 5.99 to an integer: int(5.99)?

Explanation: int() truncates floats, removing all numbers after the decimal point, returning 5.

Question 3: Which function converts a number to its text string representation?

Explanation: The str() function converts variables to string datatype.

Question 4: What is the result of running: float(7)?

Explanation: float() adds a .0 decimal fraction to integer arguments, yielding 7.0.

Question 5: What error occurs if you try to execute: int('python')?

Explanation: A ValueError is raised because 'python' cannot be converted to a base-10 integer.

Question 6: What does float('3.5') evaluate to?

Explanation: float('3.5') parses the numeric string and yields the decimal float value 3.5.

Question 7: What is the value of str(10.5)?

Explanation: str(10.5) wraps the decimal value in quotes, making it text string '10.5'.

Question 8: Which casting expression correctly adds a string number '5' and integer 10?

Explanation: Casting '5' to an integer with int() allows it to be mathematically added to 10.

Question 9: Does int() round floats to the nearest integer?

Explanation: int() always truncates floats, cutting off the fractional portion without rounding.

Question 10: What is the output of print(int(float('3.8')))?

Explanation: float('3.8') parses to float 3.8. Passing this to int() truncates it to integer 3.

🖥️ Output Prediction Challenges

Read each code snippet carefully, analyze its execution flow, and predict the exact string result written to the console.

Challenge 1 of 5

Predict the output of the code snippet below. Type the exact output in the console.

x = int(8.9)
print(x)
Console ready. Type your prediction below...
Challenge 2 of 5

Predict the output of the code snippet below. Type the exact output in the console.

x = float("10")
print(x)
Console ready. Type your prediction below...
Challenge 3 of 5

Predict the output of the code snippet below. Type the exact output in the console.

x = str(25)
print(x + "5")
Console ready. Type your prediction below...
Challenge 4 of 5

Predict the output of the code snippet below. Type the exact output in the console.

x = int("5") * 2
print(x)
Console ready. Type your prediction below...
Challenge 5 of 5

Predict the output of the code snippet below. Type the exact output in the console.

x = float(int(4.9))
print(x)
Console ready. Type your prediction below...

🎮 Interactive Code Playground

Type your own Python code below and click "Run Code" to execute it instantly in your browser!

📝 Python Code Editor
Python WebAssembly runtime is unloaded. Click 'Run Code' to load.
🖥️ Output Console
Console ready.
💬 Teacher Consultation

Stuck on any concept, or want to explore an edge case? Don't hesitate to ask follow-up questions to your instructor! Active questioning helps build storage strength.

📋 Progress Status

Lesson Complete?

📌 Check the box above to mark this weekend's lesson complete. Your dashboard status ring will update automatically.