Python Typecasting

Introduction to Typecasting

In the realm of programming, data types serve as blueprints for how data is stored and manipulated within a computer’s memory. Python, known for its dynamic typing, allows variables to hold values of different data types. Typecasting, also known as type conversion, is the process of changing the data type of a value to another compatible data type. This becomes crucial when performing operations that require specific data types or when you need to represent data in a different format.

Why Typecasting?

  • Compatibility: Certain operations or functions demand specific data types.
  • Data Representation: Changing how data is displayed (e.g., converting a number to a string).
  • Precision Control: Managing the level of detail in numeric values.

Implicit Typecasting (Automatic Conversion)

Python gracefully handles some type conversions automatically, which is known as implicit typecasting. This typically happens when there’s no risk of data loss. This typically happens during arithmetic operations or comparisons involving different data types. Python aims to make your code cleaner and more concise by handling these conversions behind the scenes.

  • Data Type Hierarchy: Python follows a data type hierarchy where certain types are considered “broader” than others. For example, float is broader than int.
  • Promotion: When combining different data types, the narrower type is usually promoted to the broader type.
  • No Explicit Action Required: You don’t need to write any extra code to trigger implicit typecasting.

Examples:

result = 5 + 3.14 # result is 8.14 (float)

The integer 5 is implicitly converted to a float before the addition.

result = 2.71 + 8 # result is 10.71 (float)

The integer 8 is implicitly converted to a float to match the type of 2.71.

result = 10 / 4.0 # result is 2.5 (float)

When you divide any number by a float, the result is always a float. This ensures that you don’t lose any decimal precision during the calculation. Even though 10 is an integer, Python automatically converts it to a float (10.0) before performing the division.

result = 10 // 3.0 # result is 3.0 (float)

Floor division with a float operand results in a float, representing the largest whole number less than or equal to the result.

result = 5 + 2.5 * 2 # result is 10.0 (float)

The multiplication is performed first, resulting in 5.0. Then, 5 is implicitly converted to 5.0, and the addition is performed, yielding 10.0.

result = 2 ** 3.0 # result is 8.0 (float)

The base 2 is implicitly converted to a float to match the exponent 3.0.

Explicit Typecasting (Manual Conversion)

Explicit typecasting is when you explicitly instruct Python to change the data type of a value. When you need more control or when dealing with potentially incompatible data types, you use explicit typecasting. Python provides built-in functions for this purpose:

  • int() – Converts to integer
  • float() – Converts to floating-point number
  • str() – Converts to string
  • bool() – Converts to Boolean (True or False)

Examples:

age_str = “28”

age_int = int(age_str)  # age_int is now 28

age_str = “xyz”

age_int = int(age_str)  # Throws a ValueError

The int() function converts a string containing only digits to its integer equivalent. Throws a ValueError if the string contains non-numeric characters.

price_str = “19.99”

price_float = float(price_str)  # price_float is now 19.99

price_str = “abc”

price_float = float(price_str) # Throws a ValueError

The float() function converts a string containing a valid floating-point representation to its numerical equivalent. Throws a ValueError if the string contains invalid characters.

pi = 3.14159

pi_int = int(pi)  # pi_int is now 3 (decimal part is truncated)

The int() function converts a float to an integer by discarding the decimal portion. This means 3.14159 becomes 3.

year = 2024

year_str = str(year)  # year_str is now “2024”

The str() function converts the integer 2024 into a string “2024”. This is useful when you want to combine numbers with text or display them in a user interface.

temperature = 25.5

temp_str = str(temperature)  # temp_str is now “25.5”

Similar to the previous example, str() converts the float 25.5 into the string “25.5”.

is_valid = True

valid_int = int(is_valid)  # valid_int is now 1 (True is 1, False is 0)

In Python, True is equivalent to the integer 1, and False is equivalent to 0. The int() function performs this conversion explicitly.

is_active = False

active_str = str(is_active)  # active_str is now “False”

The str() function converts the boolean value False into the string “False“.

zero = 0

zero_bool = bool(zero)  # zero_bool is False 

The bool() function converts the integer value 0 to False. Any non-zero integer value would be converted to True.

Interview Questions

Ans. Typecasting, also known as type conversion, is the process of changing the data type of a value to another compatible type. It’s important because certain operations or functions in Python require specific data types, and typecasting helps ensure compatibility and correct results.

Ans. The two main types are:

  • Implicit Typecasting: Python automatically converts data types in certain situations, such as when performing arithmetic operations with mixed types (e.g., integer and float). This aims to prevent data loss and simplify code.
  • Explicit Typecasting: The programmer explicitly instructs Python to change a value’s data type using functions like int(), float(), str(), and bool(). This offers more control when you need to handle potentially incompatible types or want a specific representation.

Ans. 

result = 10 / 4.0   # result is 2.5 (float)

Even though 10 is an integer, Python automatically converts it to a float (10.0) before performing the division. This is because division with a float operand always results in a float, ensuring no loss of decimal precision.

Q. In what scenarios would you typically use explicit typecasting?

Ans. You’d use explicit typecasting when:

  • User Input: Converting user input (often received as strings) into the appropriate data type for calculations or comparisons.
  • Data Manipulation: Changing the format of data for display or storage purposes (e.g., converting a number to a string for concatenation).
  • Controlling Precision: Explicitly converting floats to integers to truncate decimal values when precision isn’t needed.

Ans. Yes, a couple of things to watch out for are:

  • Data Loss: When converting floats to integers, the decimal part is truncated, potentially losing information.
  • Errors: Trying to convert incompatible types (e.g., a string with non-numeric characters to an integer) will raise errors. It’s important to validate input before typecasting.

Coding Problems

birth_year = “1995”

Calculate and print their age in the current year (2024) as an integer.

Ans. 

current_year = 2024

age = current_year – int(birth_year)  # Convert birth_year to int

print(age)  # Output: 29

quiz1 = “85”

quiz2 = “92.5”

quiz3 = “78”

Calculate and print their average grade as a floating-point number.

Ans. 

total = float(quiz1) + float(quiz2) + float(quiz3)  

average = total / 3

print(average)  # Output: 85.16666666666667

name = “Alice”

age = 30

Create a string that says “Alice is 30 years old” and print it.

Ans. 

message = name + ” is ” + str(age) + ” years old”

print(message)  # Output: Alice is 30 years old

Q. You have the price of an item as a string:

price_str = “14.99”

Calculate the price with a 15% discount and print it as a floating-point number.

Ans.

price = float(price_str)

discount = price * 0.15

final_price = price – discount

print(final_price)  # Output: 12.7415

age = 18

Determine if the person is an adult (18 or older) and print “True” if they are, or “False” if they aren’t.

Ans.  

is_adult = str(bool(age >= 18))  # Convert the comparison result to boolean, then to string

print(is_adult)  # Output: True

Code snippet based questions

num1 = “5”

num2 = 10

result = num1 + num2

print(result) 

Ans. This code will result in a TypeError. The + operator cannot directly add a string (num1) and an integer (num2). You would need to explicitly convert num1 to an integer using int(num1) before performing the addition.

value = True

doubled = value * 2

print(doubled)

Ans. The value of doubled will be 2. In Python, True is equivalent to the integer 1, so multiplying it by 2 results in 2.

mystery = 3.14

whole_number = int(mystery)

result = str(whole_number) + ” pies”

print(result)

Ans. This code will print “3 pies”.

  1. mystery is a float (3.14).
  2. int(mystery) converts it to an integer (3), truncating the decimal.
  3. str(whole_number) converts the integer 3 to a string “3”.
  4. Finally, the string “3” is concatenated with the string ” pies” to form “3 pies”.

score = 85

passing = score >= 70

result = float(passing)

print(result)

Ans. The output will be 1.0. Here’s why:

  1. score >= 70 evaluates to True since 85 is greater than or equal to 70.
  2. True is equivalent to the integer 1.
  3. float(passing) converts True (which is treated as 1) to the floating-point number 1.0.