Python lesson 14
Type Casting
Convert between numbers and text so your data is always the right shape!
Changing a Value's Type
Every value in Python has a type. Int, float, str, bool. Sometimes you need to switch types. Int() converts to a whole number. Float() converts to a decimal. Str() converts to text. Type() tells you what type a value currently is. Note: in this browser environment, we use variables instead of input() to simulate user data.
text = "42"
number = int(text) # "42" → 42
print(type(number)) # <class 'int'>
text = "42"
number = int(text)
print(number)
print(type(number))
Text Plus Text
a = "2"
b = "3"
print(a + b)
print(int(a) + int(b))
String to Number
Click Run to see a string "42" converted to an integer so we can do math with it.
Hint: Click Run! Without int(), adding 8 to "42" would crash because you cannot add a number to a string.
text_number = "42"
number = int(text_number)
result = number + 8
print("Result:", result)
print("Type:", type(result))
Average Calculator
Three scores arrive as strings. Use float() to convert them before adding. Run to see the average!
Hint: float() works just like int() but keeps decimal precision. Try changing the scores to see the average update.
score1 = "85"
score2 = "92"
score3 = "78"
total = float(score1) + float(score2) + float(score3)
average = total / 3
print("Average:", average)
Tip Calculator
A bill arrives as a string. Convert it to a float, calculate an 18% tip, and print the totals. Change the bill amount and run again!
Hint: round(number, 2) keeps two decimal places. Try bill_text = "20.00" or "100.00" to verify the 18% calculation.
bill_text = "47.50"
bill = float(bill_text)
tip = bill * 0.18
total = bill + tip
print("Bill:", bill)
print("Tip:", round(tip, 2))
print("Total:", round(total, 2))
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.