Type conversion helps you change data from one kind to another, like turning numbers into words or words into numbers. This is useful because computers treat different types of data differently.
0
0
Type conversion (int, float, string) in Python
Introduction
When you get input from a user as text but need to use it as a number for math.
When you want to show a number as part of a sentence or message.
When you need to store or send data in a specific format, like saving a number as text.
When combining different types in calculations or printing, and they must match.
When reading data from files or the internet that comes as text but should be numbers.
Syntax
Python
int(value) float(value) str(value)
int() converts to whole numbers (no decimals).
float() converts to numbers with decimals.
str() converts any value to text.
Examples
This changes text that looks like a number into an actual number you can use in math.
Python
int('123') # converts string '123' to number 123
This changes text with decimals into a decimal number.
Python
float('3.14') # converts string '3.14' to number 3.14
This changes a number into text so you can join it with other text.
Python
str(100) # converts number 100 to string '100'
When converting from float to int, the decimal part is removed, not rounded.
Python
int(3.99) # converts float 3.99 to int 3 (drops decimals)
Sample Program
This program shows how to convert text input to numbers and numbers to text for printing.
Python
user_input = '42' number = int(user_input) print(f"User input as number: {number}") pi_text = '3.1415' pi_number = float(pi_text) print(f"Pi as number: {pi_number}") score = 99 score_text = str(score) print("Score as text: " + score_text)
OutputSuccess
Important Notes
Trying to convert text that is not a number (like 'hello') to int or float will cause an error.
Converting float to int removes decimals without rounding.
Use type conversion to avoid errors when mixing types in operations or printing.
Summary
Type conversion changes data between numbers and text.
Use int(), float(), and str() to convert types.
Be careful with invalid conversions to avoid errors.