- Home
- /
- Python Type Casting
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Type Casting
Python Type Casting
Type casting in Python is when you manually change the data type of a value using built-in functions. This is different from automatic type conversion—you decide what the type should be.
Converting Strings to Numbers
Let’s say you’re working with numbers stored as strings. Python won’t treat them like real numbers unless you cast them.
data1 = "15"
data2 = "2.718"
data3 = "100"
converted_int = int(data1) # From string to integer
converted_float = float(data2) # From string to float
also_float = float(data3) # Even though it's an int-like string, we cast to float
print(converted_int) # Output: 15
print(converted_float) # Output: 2.718
print(also_float) # Output: 100.0
Converting Numbers to Strings
This is useful when displaying numbers in messages or combining them with other text.
age = 25
temperature = 36.6
as_string1 = str(age) # From integer to string
as_string2 = str(temperature) # From float to string
print(as_string1) # Output: "25"
print(as_string2) # Output: "36.6"
Summary
Here’s a quick guide to Python’s basic casting functions:
int()
→ Converts string or float to integer (if possible)float()
→ Converts string or int to floatstr()
→ Converts int or float to string
Important Note: You can only cast strings to numbers if the string is a valid number. Otherwise, Python will throw an error.
int("hello") # ❌ This will raise ValueError
With type casting, you can make your code more flexible and interactive—especially when dealing with user input, file data, or web forms.
Keep practicing, and you’ll see how powerful and handy this concept is in real-world projects!