What is type casting in python?

    Type casting is the process of changing the data type of a variable from one type to another. When you have data in one type, like a string, and you need it to be in another type, like an integer or float, you perform type casting to convert it.

Types of Type Casting:

  1. Implicit Type Casting
  2. Explicit Type Casting

1) Implicit Type Casting : 

      Python automatically converts one data type to another without user intervention.

For Example:

num1 = 10     # data type is int
num2 = 5.5    # data type is float
result = 10 + 5.5     

print(result) # Python automatically converts 10 (int) to 10.0 (float)

Output:

15.5 # which is float

 

2) Explicit Type Casting

       You manually convert a data type using Python's built-in functions.

Common Type Casting Functions:

  • int(): Converts data to an integer.
  • float(): Converts data to a floating-point number.
  • str(): Converts data to a string.
  • list(), tuple(), set(), dict(): Convert to list, tuple, set, or dictionary.

 For Example:

num1 = "10" 

print(type(num1)) # this code return me str, because the data is in the string format.

num2 = int(num1)

print(type(num2)) # now this return me int.

Output:

<class 'str'>
<class 'int'>

Question: Write a Python Program to get user age in integer.

age = input("Enter your age : ")

age = int(age)

print(age)
print(type(age))

Output:

Enter your age : 12
12
<class 'int'>

=== Code Execution Successful ===

 

15+ Interview Questions and Answers about Type Casting in Python

Question 1. What is type casting in Python?

Answer: Type casting is the process of converting a variable from one data type to another, such as from a string to an integer or from a float to a string.

 

Question 2. What are the two types of type casting in Python?

Answer: The two types of type casting are:

  1. Implicit Type Casting: Automatically performed by Python without user intervention.
  2. Explicit Type Casting: Manually performed by the programmer using built-in functions.

 

Question 3. Can you explain implicit type casting with an example?

Answer: Yes! Implicit type casting occurs when Python automatically converts a data type. For example:

num1 = 10      # int
num2 = 5.5     # float
result = num1 + num2  # num1 is automatically converted to float
print(result)  # Output: 15.5 (float)

 

Question 4. What is explicit type casting, and how is it done?

Answer: Explicit type casting is when the programmer manually converts a data type using built-in functions. For example:

num_str = "10"          # string
num_int = int(num_str)  # converts string to integer

 

Question 5. What are some common built-in functions used for type casting in Python?

Answer: Common type casting functions include:

  • int(): Converts to an integer.
  • float(): Converts to a floating-point number.
  • str(): Converts to a string.
  • list(), tuple(), set(), dict(): Convert to list, tuple, set, or dictionary.

 

Question 6. How do you handle type casting when the input is from the user?

Answer: You can cast user input, which is always a string, to the desired type. For example:

age = input("Enter your age: ")  # takes input as a string
age = int(age)                    # converts to integer

 

Question 7. What will happen if you try to convert a non-numeric string to an integer using int()?

Answer: It will raise a ValueError. For example:

num = int("abc")  # Raises ValueError: invalid literal for int() with base 10: 'abc'

 

Question 8. Can you give an example where implicit type casting may lead to unexpected results?

Answer: Implicit type casting may lead to loss of precision when mixing types. For example:

num1 = 5        # int
num2 = 2.5      # float
result = num1 / num2  # result is 2.0 (float), but could cause confusion in calculations involving ints.

 

Question 9. How can you convert a list to a string in Python?

Answer: You can use the join() method to convert a list to a string:

my_list = ['Hello', 'World']
my_string = ' '.join(my_list)  # Output: "Hello World"

 

Question 10. How do you convert a float to an integer, and what is the result?

Answer: You can use the int() function to convert a float to an integer. This will truncate the decimal part:

num_float = 5.7
num_int = int(num_float)  # num_int will be 5

 

Question 11. Is type casting reversible in Python?

Answer: Yes, type casting can be reversible. For example, you can convert an integer to a string and then back to an integer:

num = 10
num_str = str(num)        # converts to string
num_back = int(num_str)   # converts back to integer

 

Question 12. What will happen if you try to convert an empty string to an integer?

Answer: It will raise a ValueError. For example:

num = int("")  # Raises ValueError: invalid literal for int() with base 10: ''

 

Question 13. Can you give an example where type casting is necessary?

Answer: Type casting is necessary when performing mathematical operations with mixed data types. For example:

num1 = input("Enter a number: ")  # user inputs "5"
num2 = 2
result = int(num1) + num2  # We must convert num1 to int before addition.

 

Question 14. What is the difference between float() and int()?

Answer: float() converts a value to a floating-point number, while int() converts a value to an integer (truncating any decimal part). For example:

num_float = float(5)  # Output: 5.0
num_int = int(5.9)    # Output: 5

 

Question 15. How can you convert a string that represents a list back into a list?

Answer: You can use the ast.literal_eval() function from the ast module:

Leave a comment

You must be logged in to post a comment.

0 Comments