Type Casting Programs (5 Programs)
Program 1: Convert String to Integer and Perform Arithmetic Operations
Program:
# Define a string representing an integer
num_str = "25"
# Convert the string to an integer
num_int = int(num_str)
# Perform arithmetic operations
sum_value = num_int + 10
product = num_int * 3
print("Original String:", num_str)
print("Converted to Integer:", num_int)
print("Sum with 10:", sum_value)
print("Product with 3:", product)
Expected Output:
Original String: 25
Converted to Integer: 25
Sum with 10: 35
Product with 3: 75
Program 2: Convert Integer to Float and Perform Division
Program:
# Define an integer
integer_value = 15
# Convert integer to float
float_value = float(integer_value)
# Perform division with another float
result = float_value / 4.0
print("Integer:", integer_value)
print("Converted to Float:", float_value)
print("Division Result (Float):", result)
Expected Output:
Integer: 15
Converted to Float: 15.0
Division Result (Float): 3.75
Program 3: Convert Float to String and Concatenate
Program:
# Define a float value
float_val = 3.14159
# Convert float to string
str_val = str(float_val)
# Concatenate with another string
concatenated = "Pi is approximately " + str_val
print("Float Value:", float_val)
print("Converted to String:", str_val)
print("Concatenated String:", concatenated)
Expected Output:
Float Value: 3.14159
Converted to String: 3.14159
Concatenated String: Pi is approximately 3.14159
Program 4: Convert List to Set to Remove Duplicates
Program:
# Define a list with duplicate elements
num_list = [1, 2, 2, 3, 4, 4, 5]
# Convert list to set to remove duplicates
num_set = set(num_list)
print("Original List:", num_list)
print("Converted to Set (Unique Values):", num_set)
Expected Output:
Original List: [1, 2, 2, 3, 4, 4, 5]
Converted to Set (Unique Values): {1, 2, 3, 4, 5}
Program 5: Convert Dictionary Keys and Values to Lists
Program:
# Define a dictionary with some key-value pairs
student_grades = {"Alice": 88, "Bob": 92, "Charlie": 85}
# Convert dictionary keys and values to separate lists
keys_list = list(student_grades.keys())
values_list = list(student_grades.values())
print("Dictionary:", student_grades)
print("Keys as List:", keys_list)
print("Values as List:", values_list)
Expected Output:
Dictionary: {'Alice': 88, 'Bob': 92, 'Charlie': 85}
Keys as List: ['Alice', 'Bob', 'Charlie']
Values as List: [88, 92, 85]