Type Casting in Python: Convert Data Types Easily (Beginner Guide)
๐ Type Casting in Python
Complete Guide
Implicit · Explicit · int · float · str · bool · List ↔ Tuple ↔ Set
Type casting (also called type conversion) is the process of converting a value from one data type to another. For example, converting a string "5" to an integer 5, or an integer to a float. Python provides built-in functions to perform type conversions easily and quickly in your programs.
x = "10" # x is a string y = int(x) # convert to int print(y + 5) # 15 print(type(y)) # <class 'int'>
Type casting is needed because Python does not automatically mix types in operations. For example, you cannot add a string and a number — it causes a TypeError. All user input from input() comes as a string by default, so you must convert it before doing math. Type casting makes your programs flexible and error-free.
# input() always returns a string age = input("Enter age: ") # "18" (string) # ❌ This will fail # print(age + 1) → TypeError # ✅ Convert first age = int(age) print(age + 1) # 19
Implicit casting happens automatically — Python converts one data type to another without you asking. This usually happens when you mix an integer and a float in an expression. Python promotes the smaller type (int) to the larger type (float) to prevent data loss. You do not need to write any conversion code.
x = 5 # int y = 2.5 # float z = x + y # int + float print(z) # 7.5 print(type(z)) # <class 'float'> # int + bool (True = 1) print(10 + True) # 11
<class 'float'>
11
Explicit casting is when YOU manually convert a value from one type to another using Python's built-in type conversion functions. You choose when and how the conversion happens. This gives you full control over your data types. The main functions are int(), float(), str(), bool(), list(), tuple(), and set().
| Function | Converts To | Example |
|---|---|---|
| int() | Integer | int("5") → 5 |
| float() | Float | float(3) → 3.0 |
| str() | String | str(10) → "10" |
| bool() | Boolean | bool(0) → False |
| list() | List | list((1,2)) → [1,2] |
| tuple() | Tuple | tuple([1,2]) → (1,2) |
| set() | Set | set([1,1,2]) → {1,2} |
The int() function converts a value to an integer. It can convert strings that look like numbers, floats (removes decimal), and booleans. It cannot convert a string that contains letters or special characters.
print(int("10")) # 10 — from string print(int(3.99)) # 3 — float (truncated) print(int(True)) # 1 print(int(False)) # 0 # ❌ Cannot convert non-numeric string # int("hello") → ValueError!
int() truncates — it does NOT round. int(3.99) gives 3, not 4.The float() function converts a value to a floating-point (decimal) number. It can convert integers, numeric strings, and booleans. It is useful when you need decimal precision in your calculations.
print(float(5)) # 5.0 — from int print(float("3.14")) # 3.14 — from string print(float("7")) # 7.0 — string int print(float(True)) # 1.0 print(float(False)) # 0.0
3.14
7.0
1.0
0.0
The str() function converts any value to a string. This is very useful when you want to combine a number with a string in a sentence, or when you need to display a number as text. Almost any value can be converted to a string.
print(str(42)) # "42" print(str(3.14)) # "3.14" print(str(True)) # "True" print(str([1,2,3])) # "[1, 2, 3]" # Combine number + string age = 18 print("Age: " + str(age)) # "Age: 18"
str() when concatenating numbers with strings. Or use f-strings: f"Age: {age}"The bool() function converts a value to either True or False. In Python, most values are considered truthy (return True). Only a few values are falsy (return False): zero, empty string, empty list, empty dict, empty tuple, empty set, and None.
# Truthy values → True print(bool(1)) # True print(bool("hello")) # True print(bool([1,2])) # True # Falsy values → False print(bool(0)) # False print(bool("")) # False print(bool([])) # False print(bool(None)) # False
0, 0.0, "", [], {}, (), set(), None, FalsePython makes it easy to convert between collection types — list, tuple, and set. This is very useful when you need to change mutability, remove duplicates, or use a different data structure for a specific operation.
my_list = [1, 2, 3, 2] my_tuple = (4, 5, 6) my_set = {7, 8, 9} # List → Tuple and Set print(tuple(my_list)) # (1, 2, 3, 2) print(set(my_list)) # {1, 2, 3} (removes dup) # Tuple → List and Set print(list(my_tuple)) # [4, 5, 6] print(set(my_tuple)) # {4, 5, 6} # Set → List and Tuple print(list(my_set)) # [7, 8, 9] print(tuple(my_set)) # (7, 8, 9)
The input() function always returns a string, no matter what the user types. This means if the user types 25, Python receives it as the string "25". You must always convert user input to the correct type before performing operations like math.
# Get two numbers and add them a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print("Sum:", a + b) # Get a price with decimals price = float(input("Enter price: ")) print("With tax:", price * 1.1)
input() output. Use int() for whole numbers, float() for decimals.name = input("Student name: ") marks = float(input("Enter marks: ")) if marks >= 50: print(name, "- Passed ✅") else: print(name, "- Failed ❌")
qty = int(input("Quantity: ")) price = float(input("Price per item: ")) total = qty * price print("Total: Rs." + str(round(total, 2)))
x = "42" # string y = int(x) # → int = 42 z = float(y) # → float = 42.0 w = bool(z) # → bool = True s = str(w) # → str = "True" print(x, y, z, w, s)
Type conversion can fail and raise exceptions when the value cannot be converted. The most common error is ValueError — when you try to convert a non-numeric string to int or float. Always be careful with user input.
❌ ValueError — non-numeric string:int("hello") # ValueError! float("abc") # ValueError! int("3.14") # ValueError! (has dot)
int([1, 2, 3]) # TypeError! float(None) # TypeError!
try-except to handle conversion errors safely.Use a try-except block to safely handle type conversion errors. This prevents your program from crashing when invalid input is given. It catches the error and lets you handle it gracefully by showing a friendly message instead of a crash.
def safe_int(value): try: return int(value) except ValueError: print(f"Cannot convert '{value}' to int") return None print(safe_int("25")) # 25 print(safe_int("hello")) # Cannot convert... None
while True: try: age = int(input("Enter your age: ")) break # exit if valid except ValueError: print("Please enter a valid number!") print("Age is:", age)
n = input("Number: ") # "5" string print(n + 3) # TypeError! # Fix: n = int(input(...))
int("3.14") # ValueError! # Fix: float("3.14") → then int() int(float("3.14")) # ✅ = 3
print(int(9.9)) # 9 (not 10!) # Fix: use round() if rounding needed print(round(9.9)) # 10 ✅
input() to the correct type immediatelyfloat("3.14") before int() for decimal stringsround() when rounding matters — not just int()str() for simple concatenation
Comments
Post a Comment