InterviewQAs

Python Type Conversion

Download as PDF
All questions in this page are included
Preparing…
Download PDF
PTC
Python Type Conversion

Python type conversion, also called type casting, is the process of converting a value from one data type to another. This is essential when handling input from different sources, performing calculations, or interacting with external systems.

There are two main forms of type conversion in Python: implicit and explicit. Implicit conversion is automatic, performed by Python to prevent data loss, such as converting an integer to a float during arithmetic operations. Explicit conversion, or casting, requires the developer to invoke functions like int(), float(), str(), list(), etc.

Real-world usage often involves converting strings to numbers for computations, parsing JSON data into dictionaries, or converting between custom object types. Understanding type conversion is critical for robust error handling and avoiding unexpected behavior, especially in dynamic-typed languages like Python.

Advanced scenarios include handling edge cases where conversion might fail, such as converting non-numeric strings to integers, or working with complex numbers. Python provides exception handling mechanisms to manage such cases gracefully.

Effective use of type conversion improves code readability, prevents runtime errors, and enables interoperability between modules, APIs, and databases. Mastery of Python type conversion is a hallmark of writing clean, professional, and maintainable code.

Question 01

Explain the difference between implicit and explicit type conversion in Python.

EASY

Implicit type conversion, or coercion, occurs automatically in Python when performing operations that involve multiple data types. For example, adding an integer and a float automatically converts the integer to a float to prevent data loss.

Explicit type conversion, also called casting, requires the programmer to manually convert a value from one type to another using functions such as int(), str(), float(), or list(). This gives full control over the conversion and is necessary when handling input data from external sources.

Understanding the difference is crucial in real-world scenarios, as implicit conversion reduces manual effort but may lead to subtle bugs if not anticipated, whereas explicit conversion ensures clarity and precise control over data types.

Question 02

Which of the following statements about Python type conversion are correct?

MEDIUM
  • A int('123') will convert the string '123' into the integer 123.
  • B float('12.34') automatically rounds the value to an integer.
  • C str(456) converts the integer 456 into a string '456'.
  • D list('abc') converts the string 'abc' into a list ['a', 'b', 'c'].

Option A is correct because int() converts a numeric string into an integer.

Option B is incorrect because float() converts a string to a floating-point number without rounding; rounding occurs separately if required.

Options C and D are correct as str() converts numbers to strings and list() splits a string into its characters as list elements.

Question 03

Write a Python program to convert a user-input string to an integer and handle invalid inputs gracefully.

EASY

The code uses int() to explicitly convert the string input to an integer. If the input is not a valid numeric string, a ValueError is raised.

Using a try-except block ensures the program handles invalid inputs gracefully without crashing, which is essential in real-world applications like form processing or command-line tools.

# Python
user_input = input('Enter a number: ')
try:
    number = int(user_input)
    print(f'Converted number: {number}')
except ValueError:
    print('Invalid input! Please enter a valid integer.')
Question 04

How does Python handle type conversion during arithmetic operations involving multiple numeric types?

MEDIUM

Python automatically promotes values to a common type in arithmetic expressions to prevent data loss. For example, when an integer is added to a float, the integer is implicitly converted to a float before the operation.

This behavior ensures precision is maintained and reduces the need for manual conversion. Similarly, operations involving complex numbers promote operands accordingly.

Understanding this implicit behavior is crucial for writing accurate calculations in finance, scientific computing, and other domains where type mismatches can lead to subtle bugs.

Question 05

Which Python functions can safely convert values to numeric types while handling edge cases?

HARD
  • A int()
  • B float()
  • C complex()
  • D eval()

int(), float(), and complex() provide controlled type conversion to integer, floating-point, and complex numbers respectively. They raise exceptions on invalid input, allowing for error handling.

eval() is unsafe because it executes arbitrary Python expressions and should not be used for type conversion in production code due to security risks.

Question 06

Convert a list of numeric strings to a list of integers using Python, handling invalid entries.

MEDIUM

This code iterates through a list of strings and attempts to convert each to an integer using int().

Invalid strings that cannot be converted are skipped via the try-except block. This approach is practical in real-world scenarios like processing CSV or JSON files with potentially dirty data.

# Python
input_list = ['10', '20', 'abc', '30']
converted_list = []
for item in input_list:
    try:
        converted_list.append(int(item))
    except ValueError:
        continue
print(converted_list)
Question 07

Consider the following Python conversions. Which statements are correct?

MEDIUM
  • A int(12.99) returns 12
  • B float('3.1415') returns 3.1415
  • C str(True) returns 'True'
  • D list(123) returns ['1', '2', '3']

int() truncates the decimal portion, so int(12.99) returns 12.

float() correctly converts a string representing a number into a float. str() converts a boolean into its string representation.

list() cannot directly convert an integer to a list, so option D is incorrect.

Question 08

Demonstrate conversion of a Python dictionary to a JSON string and back, ensuring proper type preservation.

HARD

json.dumps() converts a Python dictionary to a JSON string, while json.loads() parses it back to a dictionary.

This is essential in real-world scenarios like API communication, where data is transmitted as JSON. Types like integers, floats, strings, and booleans are preserved during the conversion.

# Python
import json

data = {'id': 101, 'name': 'Alice', 'active': True}
json_str = json.dumps(data)
restored_data = json.loads(json_str)

print('JSON string:', json_str)
print('Restored dictionary:', restored_data)
Question 09

What are some challenges when performing type conversion with user-generated input and how can they be mitigated?

HARD

User-generated input can be unpredictable, containing non-numeric strings, empty values, or special characters. Attempting direct conversion without validation may lead to exceptions and runtime errors.

To mitigate these issues, developers can use validation techniques, regular expressions, or try-except blocks to handle invalid inputs gracefully. Providing clear error messages or default fallback values enhances robustness.

In addition, understanding locale-specific formats (like commas in numbers or date representations) is crucial for accurate conversion. Libraries like decimal and locale can help handle these edge cases effectively.

Question 10

Convert a list containing mixed types (int, float, string) to floats safely, ignoring non-convertible elements.

HARD

The code iterates through a mixed-type list and attempts to convert each element to a float. Invalid conversions are ignored using try-except blocks.

This approach is practical for data cleaning in analytics pipelines, ETL processes, or preprocessing input from CSV, Excel, or user forms where data may be inconsistent.

# Python
mixed_list = [10, '20.5', 'abc', 30.0, '40']
float_list = []
for item in mixed_list:
    try:
        float_list.append(float(item))
    except ValueError:
        continue
print(float_list)
Question 11

Why is using Decimal preferred over float in some type conversion scenarios?

MEDIUM

The float type in Python uses binary floating-point representation, which can introduce small precision errors during arithmetic operations. These inaccuracies are acceptable in many applications but become problematic in financial systems, billing engines, or tax calculations.

The Decimal class from Python's decimal module provides fixed-point and floating-point arithmetic with better precision control. When converting user-entered currency values such as '19.99', Decimal preserves the exact value instead of storing an approximated binary representation.

In production systems involving payments or accounting, converting strings directly to Decimal instead of float prevents rounding inconsistencies. This becomes especially important when aggregating thousands of transactions where tiny errors can accumulate into major discrepancies.

Question 12

Write a Python program that converts comma-separated numeric values from a string into integers while removing extra spaces.

MEDIUM

The split() function separates the string into individual elements using commas. The strip() method removes unwanted whitespace before conversion.

This pattern is commonly used while processing CSV-like input from configuration files, API query parameters, or user-entered values in web forms.

# Python
raw_data = '10, 20,  30,40 , 50'

numbers = [int(value.strip()) for value in raw_data.split(',')]

print(numbers)
Question 13

Which conversion operation raises a ValueError exception?

EASY
  • A int('50')
  • B float('12.5')
  • C int('10.2')
  • D str(100)

The string '10.2' represents a floating-point value and cannot be directly converted using int(). Python raises a ValueError because the format is invalid for integer parsing.

A safer approach is converting the value to float first and then to int() if truncation is acceptable.

Question 14

Create a Python function that safely converts nested dictionary values to integers where possible.

HARD

The function recursively traverses nested dictionaries and attempts integer conversion on each value. Invalid conversions are skipped without interrupting execution.

This pattern is useful in ETL systems and API normalization layers where incoming payloads may contain inconsistent data types represented as strings.

# Python
sample_data = {
    'age': '30',
    'profile': {
        'experience': '8',
        'rating': '4.7',
        'department': 'Engineering'
    }
}


def convert_to_int(data):
    for key, value in data.items():
        if isinstance(value, dict):
            convert_to_int(value)
        else:
            try:
                data[key] = int(value)
            except (ValueError, TypeError):
                pass


convert_to_int(sample_data)
print(sample_data)
Question 15

What are the risks of aggressive automatic type conversion in backend applications?

HARD

Aggressive automatic conversion can silently change the meaning of data. For example, converting all numeric-looking strings into integers may unintentionally remove leading zeros from employee IDs, ZIP codes, or account numbers.

Another major risk is data corruption caused by unexpected truncation or precision loss. Converting floating-point strings to integers without validation may discard meaningful decimal information used in analytics or reporting systems.

Experienced developers implement validation rules before conversion instead of relying on assumptions. This ensures business-critical identifiers and financial values remain accurate throughout the application's lifecycle.

Question 16

Which statements about bool conversion in Python are correct?

MEDIUM
  • A bool(0) returns False
  • B bool('False') returns False
  • C bool([]) returns False
  • D bool(1) returns True

Python treats empty collections and numeric zero values as False during boolean conversion. Non-empty collections and non-zero numbers evaluate to True.

The string 'False' is still considered a non-empty string, so bool('False') returns True. This often surprises developers handling configuration values or environment variables.

Question 17

Write a Python example that converts tuples into dictionaries using type conversion techniques.

MEDIUM

The dict() constructor converts an iterable containing key-value pairs into a dictionary. Each tuple becomes a dictionary entry.

This conversion pattern is commonly used while transforming database query results, API responses, or configuration mappings into structured Python objects.

# Python
employee_data = [('id', 101), ('name', 'Vijay'), ('role', 'Architect')]

employee_dict = dict(employee_data)

print(employee_dict)
Question 18

Which operations may lead to unintended data loss during type conversion?

HARD
  • A int(9.99)
  • B str(100)
  • C set([1, 1, 2, 2])
  • D float('15')

Converting 9.99 to int truncates the decimal portion and results in 9, causing precision loss.

Converting a list to a set removes duplicate values automatically. While useful for deduplication, it may unintentionally discard meaningful repeated entries in transactional or audit data.

Question 19

Write a Python program that converts a string into a list of words and then converts the list back into a sentence.

EASY

The split() method converts a string into a list using whitespace as the delimiter, while join() reconstructs the string from list elements.

This pattern is widely used in text preprocessing, log parsing, chatbot systems, and search indexing pipelines.

# Python
sentence = 'Python type conversion is powerful'

word_list = sentence.split()
print(word_list)

reconstructed = ' '.join(word_list)
print(reconstructed)
Question 20

How can custom classes support type conversion behavior in Python?

MEDIUM

Python allows developers to define custom conversion behavior using special methods such as __int__(), __float__(), __str__(), and __bool__(). These methods control how objects behave when passed into conversion functions.

For example, a Currency class can implement __float__() so pricing objects can participate naturally in calculations. Similarly, __str__() can provide clean human-readable formatting for logging or reporting.

This capability is especially valuable in enterprise applications because it allows domain objects to integrate seamlessly with Python's built-in conversion ecosystem while maintaining encapsulation and readability.

Question 21

Explain the difference between converting using int() and using math.floor() or math.ceil().

MEDIUM

Using int() converts a float to an integer by truncating the decimal portion toward zero. It does not round the number, so int(3.9) becomes 3, and int(-3.9) becomes -3.

math.floor() and math.ceil(), on the other hand, round numbers toward negative or positive infinity. math.floor(3.9) returns 3, but math.floor(-3.9) returns -4. math.ceil(3.1) returns 4, and math.ceil(-3.1) returns -3.

In real-world applications like financial calculations or coordinate mapping, choosing between int() and floor()/ceil() impacts the results, so understanding their differences is crucial to prevent subtle logic errors.

Question 22

Write a Python program to convert a list of mixed numeric strings and numbers into floats and filter out negative values.

MEDIUM

The code iterates through mixed values and converts them to float using explicit type conversion.

Invalid entries such as 'abc' are skipped, and negative numbers are filtered out. This approach is common in data preprocessing and cleaning pipelines before statistical or ML processing.

# Python
mixed_list = ["10.5", -3, "7.8", 0, "abc", -5.2]

float_list = []
for item in mixed_list:
    try:
        val = float(item)
        if val >= 0:
            float_list.append(val)
    except ValueError:
        continue

print(float_list)
Question 23

Which statements about converting strings to numbers are true?

MEDIUM
  • A int('100') returns 100
  • B float('3.14') returns 3
  • C int('0x10', 16) returns 16
  • D int('010') returns 10

int('100') correctly converts a decimal string to an integer.

int('0x10', 16) allows base-16 conversion, returning 16.

int('010') returns 10 in Python 3 since octal literal notation with leading zero is not used.

float('3.14') returns 3.14, not 3, so that option is false.

Question 24

How can you safely convert a deeply nested JSON structure with mixed types in Python?

HARD

Deeply nested JSON structures often contain strings, numbers, booleans, and null values. Converting them requires a recursive approach that checks types before applying conversions.

You can implement helper functions that traverse the JSON tree, converting compatible types (like numeric strings to numbers) and skipping or logging incompatible values.

This is especially useful in ETL pipelines and API data ingestion, where input data may be inconsistent and preserving type integrity is crucial for downstream processing.

Question 25

Convert a dictionary with string numeric keys and values to integers safely in Python.

HARD

The code attempts to convert both keys and values to integers. Entries that cannot be converted are skipped.

This pattern is common when processing dynamic data where keys may come from user input, CSV files, or JSON payloads and must be numeric for indexing or computation.

# Python
data = {'1': '10', '2': '20', 'three': '30'}
converted = {}

for k, v in data.items():
    try:
        new_k = int(k)
        new_v = int(v)
        converted[new_k] = new_v
    except ValueError:
        continue

print(converted)
Question 26

Which of the following conversions can preserve the exact value?

MEDIUM
  • A str(123.45)
  • B int(123.45)
  • C float('123.45')
  • D Decimal('123.45')

Converting to string or Decimal preserves the exact numeric representation.

int(123.45) truncates the decimal portion, resulting in loss of precision.

float('123.45') preserves the floating-point value but may have minimal binary representation errors; Decimal ensures exact precision.

Question 27

Demonstrate converting a set of integers to a list and then to a comma-separated string.

MEDIUM

The set is first converted to a list to enable ordering or further operations.

Then each integer is converted to a string and joined with commas. This pattern is widely used when preparing data for CSV export, logging, or API requests.

# Python
num_set = {1, 2, 3, 4, 5}
num_list = list(num_set)
num_str = ','.join(str(n) for n in num_list)

print(num_str)
Question 28

What precautions should you take when converting floats to integers in Python?

MEDIUM

When converting floats to integers, Python truncates the decimal portion toward zero, which can lead to loss of information. It is important to understand whether truncation, rounding, or flooring is required for your specific use case.

In financial or scientific applications, truncation without proper handling can result in cumulative errors. Using rounding functions like round(), math.floor(), or math.ceil() may be more appropriate depending on business rules.

Always validate input and consider negative numbers, NaN, or infinite values before converting to integers to avoid runtime exceptions or unintended results.

Question 29

Which statements about type conversion with Python's json module are correct?

HARD
  • A json.dumps() converts Python objects to JSON strings
  • B json.loads() converts JSON strings to Python objects
  • C json.loads() always preserves data types exactly
  • D json.dumps() can convert sets directly to JSON arrays

json.dumps() serializes Python dictionaries, lists, strings, numbers, and booleans to JSON strings, but cannot directly serialize sets.

json.loads() deserializes JSON strings back into Python objects, but JSON does not distinguish between ints and floats in some cases, so exact type preservation is not guaranteed.

Question 30

Convert a list of mixed-type items (numbers, numeric strings, booleans) to integers where possible, treating True as 1 and False as 0.

HARD

Booleans are explicitly converted to integers (True ? 1, False ? 0). Numeric strings and floats are converted to int via float to handle decimal strings.

Invalid entries like 'abc' are skipped. This approach is practical in ETL pipelines, data normalization, or analytics workflows handling inconsistent mixed-type data.

# Python
mixed = [10, '20', 3.5, True, False, 'abc']
converted = []

for item in mixed:
    try:
        if isinstance(item, bool):
            converted.append(int(item))
        else:
            converted.append(int(float(item)))
    except (ValueError, TypeError):
        continue

print(converted)