Python: Type Casting

As you are now already familiar with the input function which is used for data input. Also, you must be familiar now that the input function returns data as String type. Scenarios where you want your users to input the value as a number (int or float type). Python provides functions to typecast String types to numbers and numbers to String types.

Type Casting (or type conversion) allows you to change the data type of a variable.

operand = int (input ('Enter the Number: '))
operand = float (input ('Enter Number in fractional value'))
print('You entered the value = + str(operand))

There are two main types of type casting:

  1. Implicit Type Casting: In this method, Python automatically converts one data type into another without user intervention.
  2. Explicit Type Casting: In this method, you explicitly convert a variable to a specific data type using predefined functions.

Examples

Python implicitly converts a (an integer) to a float for addition and multiplication.

a = 7
b = 3.0
c = a + b     # Result: 10.0 (float)
d = a * b     # Result: 21.0 (float)

Convert int to float

a = 5
n = float(a)     # Result: 5.0 (float)

Convert float to int

a = 5.9
n = int(a)  # Result: 5 (integer)

Convert int to str

a = 5
n = str(a)  # Result: '5' (string)

Convert str to float:

a = "5.9"
n = float(a)  # Result: 5.9 (float)

Convert str to int (with error handling)

a = "5"
try:
    n = int(a)  # Result: 5 (integer)
except ValueError:
    print("Invalid input")