Python – Type Casting

After reading this Python type casting topic, you will know its theory, examples, you will understand how to use various type casting functions as int(), float(), and str() in Python.

Type casting means to convert variable data of one type to another type and for doing this conversion some functions are available in python are:

  • int()
  • float()
  • str()

int()

This function converts float value or a string data to integer value.

Example:

Program (1): To demonstrate how to convert float value to integer value in Python.

x=int(2.7)
print(x)
print(type(x))

Output(1)

2
<class 'int'>

Explanation: for Program(1) and Output(1)

  • x is variable.
  • 2.7 is float value input to int() function as int(2.7).
  • int(2.7) gives integer value as 2 stored in variable x.
  • type(x) function used inside print statement (i.e. print(type(x))) to prove that variable x stores integer value.

float()

This function convert integer value or a string data to float value.

Example:

Program (1): To demonstrate how integer value converts to float value in Python.

x=float(2)
print(x)
print(type(x))

Output(1)

2.0
<class 'float'>

Explanation: for Program(1) and Output(1)

  • x is variable.
  • 2 is integer value input to float() function as float(2).
  • float(2) gives float value as 2.0 stored in variable x.
  • type(x) function used inside print statement (i.e. print(type(x))) to prove that variable x stores float value.

str()

This function convert float value or integer value to string data.

Example:

Program (1): To demonstrate how integer value converts to string in Python.

x=str(2)
print(x)
print(type(x))

Output(1)

2
<class 'str'>

Explanation: for Program(1) and Output(1)

  • x is variable.
  • 2 is integer value input to str() function as str(2).
  • str(2) gives string data as 2.0 stored in variable x.
  • type(x) function used inside print statement (i.e. print(type(x))) to prove that variable x stores string data.

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *