Type casting in Python

Type casting, also known as type conversion, is converting a variable from one data type to another. Here are some simple to interesting examples of type casting in Python:


Type casting, also known as type conversion, is the process of converting a variable from one data type to another.

Here are some simple to interesting examples of type casting in Python:

Integer to Float:


x = 5
y = float(x)

Float to Integer:


z = 10.75
w = int(z)

Integer to String:


age = 25
age_str = str(age)

String to Integer:


num_str = "42"
num = int(num_str)

Float to String:


height = 5.9
height_str = str(height)

String to Float:


weight_str = "68.5" 
weight = float(weight_str)

List to Tuple:


numbers_list = [1, 2, 3, 4, 5] 
numbers_tuple = tuple(numbers_list)

Tuple to List:


coordinates_tuple = (3, 4) 
coordinates_list = list(coordinates_tuple)

String to List of Characters:


word = "hello" 
char_list = list(word)

List of Strings to String:


words_list = ["Hello", "World"]
sentence = ' '.join(words_list)

Integer to Boolean:


num = 0 is_valid = bool(num)

Boolean to Integer:


is_valid = True
num = int(is_valid)

String to Boolean:


flag_str = "True"
flag = bool(flag_str)

Boolean to String:


is_valid = False
flag_str = str(is_valid)

Floating-Point to Complex:


real_part = 3.0
imaginary_part = 4.0 
complex_number = complex(real_part, imaginary_part)

String to Date:


from datetime import datetime 
date_str = "2022-01-08"
date_object = datetime.strptime(date_str, "%Y-%m-%d").date()

Some Interesting Examples:

Using type casting to check user input:


age_str = input("Enter your age: ") 
try: 
    age_int = int(age_str) 
    # Proceed with age-related calculations 
except ValueError: 
    print("Invalid age entered. Please enter a number.")

Converting lists of strings to numbers for calculations:


numbers_str = ["1","2","3","4"] 
numbers_int = [int(num) for num in numbers_str] # List comprehension for conversion
total = sum(numbers_int) # Calculate the sum of the numbers

Creating custom objects with string representation:


class Person:
    def __init__(self, name, age): 
       self.name = name 
       self.age = age 
    def __str__(self): 
       return f"Name: {self.name}, Age: {self.age}" 
    
person = Person("Alice", 30) 
person_str = str(person) # person_str will now be "Name: Alice, Age: 30"

Handling User Input Flexibly:


age_str = input("Enter your age: "") 
# Handle potential string input 
# and convert to integer 
age = int(age_str) 
print("You are", age, "years old.")

Converting ASCII Characters to Codes and Vice Versa:


char = "A" 
code = ord(char)  # Convert character to its ASCII code 
print(code)  # Output: 65 
code = 97 
char = chr(code)  # Convert ASCII code to its corresponding character 
print(char)  # Output: 'a'

These examples demonstrate various type casting operations in Python. Understanding how to convert between different data types is essential for working with diverse data in Python programs.

Some common mistakes developers make while using type casting in Python:

Assuming Success Without Verification:

Confusing int() and float():

Overlooking Data Loss:

Incorrect String Formatting:

Implicit Conversion Pitfalls:

Missing Type Checks:

Infinite Recursion with Custom Classes:

Overlooking Inheritance Issues:

By understanding these common mistakes and following best practices, you can write more robust and reliable Python code that utilizes type casting effectively.

Type Casting Quiz

What is the output of int(3.14)?

The answer is B. 3

What is the output of float('10')?

The answer is B. 10.0

What is the output of str(True)?

The answer is B. 'True'

What is the output of bool(“hello”)?

The answer is A. True

What is the output of bool(0)?

The answer is B. False

What is the output of bool(“0”)?

The answer is A. True