Chapter 3: Type Castingยถ
๐ Open Notebookยถ
๐บ Video Tutorialยถ
Learn type casting in 7 minutes! ๐ฑ (7:39)
๐ What Youโll Learnยถ
Type casting is the process of converting data from one type to another - essential for working with user input and performing calculations!
๐ฏ Learning Objectivesยถ
Understand what type casting is and why itโs needed
Learn to convert between int, float, str, and bool
Use the
type()function to check data typesHandle common type conversion scenarios
๐ Concept Explanationยถ
What is Type Casting?ยถ
Type casting (or type conversion) is the process of converting a variable from one data type to another.
Why is Type Casting Needed?ยถ
User input is always a string, even if you enter numbers
Mathematical operations require numeric types
String concatenation requires all values to be strings
Different operations work with different types
Common Type Casting Functionsยถ
int() - Convert to Integerยถ
float_num = 3.14
int_num = int(float_num) # Result: 3 (decimal is removed)
text = "25"
number = int(text) # Result: 25 (string becomes integer)
float() - Convert to Floatยถ
int_num = 25
float_num = float(int_num) # Result: 25.0
text = "3.14"
number = float(text) # Result: 3.14
str() - Convert to Stringยถ
age = 25
age_text = str(age) # Result: "25"
price = 19.99
price_text = str(price) # Result: "19.99"
bool() - Convert to Booleanยถ
number = 1
is_true = bool(number) # Result: True (any non-zero number is True)
empty_string = ""
is_false = bool(empty_string) # Result: False (empty strings are False)
The type() Functionยถ
The type() function tells you what data type a variable is:
name = "Alice"
age = 25
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
๐ก Examplesยถ
Example 1: Converting User Inputยถ
# input() always returns a string
age_str = input("Enter your age: ") # If user types "25", age_str = "25"
age_int = int(age_str) # Convert to integer: 25
print(age_int + 5) # Now we can do math: 30
Example 2: String Concatenationยถ
age = 25
# This doesn't work: print("I am " + age) # Error!
print("I am " + str(age)) # Works! Convert age to string first
# Or use f-strings (no conversion needed):
print(f"I am {age}") # Also works!
Example 3: Float to Intยถ
gpa = 3.7
gpa_int = int(gpa) # Result: 3 (truncates, doesn't round)
print(gpa_int)
โ๏ธ Practice Exercisesยถ
Ask the user for two numbers and add them (remember to convert from string to int)
Create a float variable and convert it to int, then to string
Ask user for their height in meters (float) and convert it to centimeters (int)
Create a program that asks for a price (string) and adds 10% tax, displaying the result
๐ Common Mistakesยถ
Forgetting to Convert User Inputยถ
# Wrong:
age = input("Enter age: ")
print(age + 5) # Error! Can't add string and number
# Correct:
age = int(input("Enter age: "))
print(age + 5) # Works!
Trying to Convert Invalid Stringsยถ
# This will cause an error:
text = "hello"
number = int(text) # Error! Can't convert "hello" to int
# Only numeric strings can be converted:
text = "123"
number = int(text) # Works! Result: 123
Losing Precisionยถ
pi = 3.14159
pi_int = int(pi) # Result: 3 (decimal part is lost forever!)
๐ Key Pointsยถ
input()always returns a string, even if the user types a numberint()truncates decimals (doesnโt round):int(3.9)โ3You canโt convert non-numeric strings to numbers:
int("hello")โ ErrorType casting is permanent for that variable unless you reassign it
๐ Try It Yourselfยถ
Modify main.py to create a program that:
Asks for a personโs name (string)
Asks for their age (convert to int)
Asks for their height in meters (convert to float)
Displays all information with proper types
๐ Key Takeaways from Videoยถ
Strings are text data enclosed in quotes
Follow along with the video for hands-on practice
Experiment with the code examples to deepen understanding
๐ก These points cover the main concepts from the video tutorial to help reinforce your learning.
๐ Next Chapterยถ
Continue to Chapter 4: User Input to learn how to interact with users!