In this article, you’ll learn everything you need to know about type conversion also known as type casting in python along with that you’ll also learn about their types, and how to use them with examples.

So, Let’s get started!

## What is meant by Type Casting in Python?

Type casting or simply type conversion is a **process of converting (changing) the type of a value or a variable** to **another type**

*(specified data type)*.

## Types of Casting in Python:

Basically, Python provides the following two types of casting**:**

- Implicit Type Casting
- Explicit Type Casting

### 1. Implicit Type Casting

It is a type casting in which Python interpreter automatically converts one data type to another data type.

This process does not require any user (programmer) involvement, which means, you don’t have to directly or clearly convert one data type into another data type.

When the data type conversion takes place during compilation or during run time, then it’s called an **implicit data type conversion**.

**Examples:**

```
a = 15
print("Data type of a is: ", type(a))
b= 5.0
print("Data type of b is: ", type(b))
diff = a - b
print("The difference between a and b is: ", diff)
print("Data type of diff is: ", type(diff))
```

**Output:**

```
Data type of a is: <class 'int'>
Data type of b is: <class 'float'>
The difference between a and b is: 10.0
Data type of diff is: <class 'float'>
```

As you can see in the output of the above example, type of “diff” got automatically changed to the “float” type.

There is no any user involvement or participation to directly or clearly change the given data type to another.

This happens only because, Python always converts smaller data types to larger data types (data types having more precision) to avoid the loss of data.

### 2. Explicit Type Casting

When a user manually (not-automatically) change a given data type to another data type according to his/her need, then it is called as **explicit type casting**.

In python, We use some built-in (predefined) functions like `int()`

, `float()`

, `str()`

, `list()`

, `tuple()`

, `set()`

, `bool()`

etc to perform explicit type conversion.

Which simply means, In explicit type conversion **–** We force an expression to be of a specific type with the help of some built-in functions (as I mentioned above).

**Syntax for explicit type conversion:**

`<required_datatype>(expression)`

Explicit type conversion can be done by assigning the required data type function to the expression.

? **Note:** In Explicit Type Casting, loss of data may occur as we enforce the expression or the object to a specific data type.

Don’t worry! You’ll be more clear about this later on this article with the help of some examples.

### Let’s have a quick look at some of the most commonly used built-in functions which are used to perform conversion from one data type to another.

Sr.No. | Functions & Description |
---|---|

1. | int(x [,base])Converts x to an integer. Base specifies the base of x if x is a string.By default the `base` is 10, if it is not specified, which is decimal value. |

2. | float(x)Converts x to a floating-point number. |

3. | complex(real [,imag])Creates a complex number. |

4. | bin(x)Converts an integer to a binary value. |

5. | bool(x)Converts object x to a boolean value, either `True` or `False` . |

6. | str(x)Converts object x to a string representation. |

7. | repr(x)Converts object x to an expression string (i.e., printable representation of the given x). |

8. | eval(str)Evaluates a string and returns an object (often the object would be an integer). |

9. | tuple(s)Converts s to a tuple. |

10. | list(s)Converts s to a list. |

11. | set(s)Converts s to a set. |

12. | dict(d)Creates a dictionary. d must be a sequence of (key,value) tuples. |

13. | frozenset(s)Converts s to a frozen set. |

14. | chr(x)Converts an integer to its corresponding ASCII character. |

15. | ord(x)Converts a single character to its corresponding ASCII code, which is integer value. |

16. | hex(x)Converts an integer to its corresponding hexadecimal string. |

17. | oct(x)Converts an integer to its corresponding octal string. |

**Let us understand the uses of all the above functions one by one with the help of some examples.**

**1.** **int(x [,base]):**

`int(x [,base])`

can take a `float`

, `bool`

, or `string`

literal as argument and returns a value of class `'int'`

type.

We can’t convert a complex number into `int`

type.

When we convert a **string type** to **int type**, a string must contain integral (numerical) value only and may have varied base.

And,

As we already know, Every numerical value has a base, for example**:**

**Decimal value**uses the digits`0`

to`9`

and has a base of`10`

- The
**binary value**uses the digits`0`

or`1`

and has a base of`2`

- The
**octal value**uses the digits through`0`

to`7`

and has a base of`8`

**Hexadecimal**uses the digit through`0`

to`9`

plus the letters`A`

through`F`

, and have a base of`16`

**Example:**

```
# float to int conversion
length = 5.1926 # floating point number
type(length) # type() function is used to get the type of a value or a variable
new_length = int(length) #converting float to int type using int() function
print(new_length)
type(new_length)
# string to int conversion
num_str = "1234"
type(num_str)
num_int = int(num_str) #converting string to int type using int() function
print(num_int)
type(num_int)
```

**Output:**

```
# float to int conversion
<class 'float'>
5
<class 'int'>
# string to int conversion
<class 'str'>
1234
<class 'int'>
```

**2.** **float(x):**

The `float()`

function is used to convert a given data type to floating-point numbers.

`float(x)`

function can take an `int`

, `bool`

or `string`

literal as argument and returns a value of class `'float'`

type.

**Example:**

```
# int to float conversion
num_int = 1024 # An integer value
type(num_int)
new_num = float(num_int) #converting an integer to a floating-point number using float() function
print(new_num)
type(new_num)
```

**Output:**

```
<class 'int'>
1024.0
<class 'float'>
```

**3.** **complex(real [,imag]): **

`complex()`

function is used to convert an `int`

, `float`

, `bool`

or a `string`

literal to `'complex'`

type.

The complex function has the following two forms for conversion**:**

`complex(x)`

**:**To convert a value`x`

into a`complex`

type. In this form, the real part is`x`

, and the imaginary part is`0`

.`complex(x, y)`

**:**To convert the value`x`

and`y`

into a`complex`

type. In this form, the real part is`x`

, and the imaginary part is`y`

.

**Example:**

```
# int to complex conversion
num_int = 7
num_c = complex(num_int) #converting an integer to a complex number using complex() function
print(num_c)
type(num_c)
```

**Output:**

```
(7+0j)
<class 'complex'>
```

**4.** **bin(x):**

The `bin(x)`

function takes an integer *x* as argument and returns the binary representation of *x* in a string format.

**Example:**

```
# int to binary conversion
a = 1
type(a)
b = bin(a) #converting an integer to a binary value using bin() function
print(b)
type(b)
#or
bin(a)
```

**Output**:

```
<class 'int'>
0b1
<class 'str'>
'0b1'
```

**5.** **bool(x):**

The `bool(x)`

Converts object x to a boolean value, either `True`

or `False`

.

The object x can an integer, float, complex number or any expression.

An integer, float or complex number set to *zero* returns** False**.

And, An integer, float or complex number set to any other numbers, *positive* or *negative* returns **True**.

**Example:**

```
# int to bool conversion
x = 1
y = bool(x) #converting an integer to a boolean value using bool() function
print(y)
type(y)
a= 0
b = bool(a)
print(b)
type(b)
```

**Output:**

```
True
<class 'bool'>
False
<class 'bool'>
```

**6.** **str(x):**

The `str(x)`

function takes an object *x* as argument and returns the string format of the given object *x*.

Objects can be any object. But generally, int, float, complex or boolean is used.

If you don’t provide any object as an argument inside the `str()`

function, it returns an empty string.

**Example:**

```
# int to string conversion
n_int = 999
type(n_int)
n_str = str(n_int) #converting an integer to a string using str() function
print(n_str)
type(n_str)
# or
str(999)
str() # not providing any argument inside the parentheses of str() function.
```

**Output:**

```
<class 'int'>
999
<class 'str'>
'999'
' ' # An empty sting is printed
```

**7.** **repr(x):**

The `repr(x)`

converts object x to an expression string (i.e., printable representation of the given x).

Object x can be of any data type or you can say object x can be any object.

`repr()`

takes only one argument at a time.

**Example:**

```
# complex to expression string conversion
x = 3 + 5j # declaring a complex number x
type(c)
new_obj = repr(x) #converting a complex number to a expression string using repr() function
print(new_obj)
type(new_obj)
#or
repr(x)
type(repr(x))
```

**Output: **

```
<class 'complex'>
(3+5j)
<class 'str'>
'(3+5j)'
<class 'str'>
```

**8.** **eval(str):**

The `eval(str)`

function takes an expression in the form of *string* as argument and converts it to the result of the evaluated expression (most often the return type would be a number).

Also, optionally global and locals can be used as an argument inside eval function, but the globals must be represented as a dictionary and the locals as a mapped object.

**The syntax of the eval function is as shown below:**

`eval(expression, [globals[, locals]])`

**Example:**

```
# passing an expression inside the parentheses of eval() function.
a = eval('3*2+1-3') # passing an expression in the form of a string inside the parentheses of eval() function
print(a)
type(a)
```

**Output:**

```
4
<class 'int'>
```

**9. tuple(s):**

The `tuple(s)`

function takes an object s as argument and converts s to a tuple.

**Example:**

```
# string to tuple conversion
s = "python"
type(s)
t = tuple(s) #converting a string to tuple using tuple() function
print(t)
type(t)
```

**Output:**

```
<class 'str'>
('p', 'y', 't', 'h', 'o', 'n')
<class 'tuple'>
```

**10. list(s):**

The `list(s)`

function takes an object s as argument and converts s to a list.

Object s can be a sequence (string, tuples) or collection (set, dictionary) or any iterable object.

If no parameters are passed inside the parentheses of list() function, it returns an empty list.

**Example: **

```
# tuple to list conversion
tup = (2, 4, 6, 8)
type(tup)
lst = list(tup) #converting a tuple to a list using list() function
print(lst)
type(lst)
list() # not providing any argument inside the parentheses of list() function.
```

**Output:**

```
<class 'tuple'>
[2, 4, 6, 8]
<class 'list'>
[ ] # An empty list is created
```

**11.** **set(s):**

The `set(s)`

function takes an object s as argument and converts s to a set.

Object s can be any iterable sequence like list, tuple or dictionary.

**Example:**

```
# list to set conversion
lst = [1, 2, 3, 4, 5]
type(lst)
s = set(lst) #converting a list to a set using set() function
print(s)
type(s)
```

**Output:**

```
<class 'list'>
{1, 2, 3, 4, 5}
<class 'set'>
```

**12.** **dict(d):**

The `dict(d)`

function takes an object d as argument and creates a dictionary. d must be a sequence of (key,value) tuples.

**Example:**

```
# tuple to dictionary conversion
# initializing (key, value) tuple
tup = ((1, 'one') ,(2, 'two'), (3, 'three'))
type(tup)
d = dict(tup) #converting a tuple to a dictionary using dict() function
print(d)
type(d)
```

**Output:**

```
<class 'tuple'>
{1: 'one', 2: 'two', 3: 'three'}
<class 'dict'>
```

**13. frozenset(s):**

The `frozenset(s)`

function takes an iterable object s as argument and converts s to a frozenset.

The iterable object can be a list, tuple, set or any other iterables.

**Example:**

```
# set to frozenset conversion
s = {'a', 'e', 'i', 'o', 'u'} # set of all the vowels in english alphabets
type(s)
fset = frozenset(s) # converting a set to frozenset using frozenset() function
print("frozenset is : ", fset)
type(fset)
```

**Output: **

```
<class 'set'>
frozenset is : frozenset({'i', 'a', 'o', 'e', 'u'})
<class 'frozenset'>
```

If you do not pass any argument inside the parentheses of `frozenset()`

function, it returns an empty frozenset.

**Example:**

```
print("The empty frozen set is: ", frozenset())
```

**Output:**

```
The empty frozen set is: frozenset()
```

**14.** **chr(x):**

The `chr(x)`

function takes only one integer as argument and converts that integer x to its corresponding **ASCII** character.

**Example:**

```
# integer to its corresponding ASCII character conversion
num_int = 65
type(num_int)
c = chr(num_int) # converting an integer to ASCII character using chr() function
print(c)
type(c)
```

**Output:**

```
<class 'int'>
A # ASCII character of 65 is 'A'
<class 'str'>
```

**15. ord(x):**

This is just the inverse of `chr()`

function.

The `ord(x)`

function takes only one character as argument and converts that character x to its corresponding **ASCII** code, which is integer value.

**Example:**

```
# a single character to its corresponding ASCII code conversion
ch = 'z' # declaration of a single character 'z' (lowercase z)
type(ch)
code = ord(ch) # converting a character to its corresponding ASCII code using ord() function
print(code)
>>> type(code)
```

**Output:**

```
<class 'str'>
122
<class 'int'>
```

**16. hex(x):**

The `hex(x)`

function takes an integer x as argument and converts it to its corresponding hexadecimal string.

**Example:**

```
# integer to its corresponding hexadecimal string conversion
num_int = 10
type(num_int)
H = hex(num_int) # converting an integer to hexadecimal string using hex() function
print(H)
type(H)
#or
hex(10)
type(hex(10))
```

**Output:**

```
<class 'int'>
0xa
<class 'str'>
'0xa'
<class 'str'>
```

**17. oct(x):**

The `oct(x)`

function takes an integer x as argument and converts it to its corresponding octal string.

**Example:**

```
num_int = 25
type(num_int)
new_str = oct(num_int) # converting an integer to octal string using oct() function
print(new_str)
type(new_str)
#or
oct(25)
type(oct(25))
```

**Output:**

```
<class 'int'>
0o31
<class 'str'>
'0o31'
<class 'str'>
```

## Conclusion:

In this article, you learned What is **Type conversion and Type casting in Python**, and you also became familiar with the different types of type casting in Python with lots of examples and many more…

In short**:** Type casting or simply type conversion is just a **way of converting (changing) the type of a value or a variable** to **another type**

*(specified data type)*.

So,

**I really hope that you liked my article and got a lot of value from it.**

Now, It’s your turn!

If you have any question, feel free to ask in the comment section below right now.

And,

Don’t forget to share this article to your lovely friends.

Sharing is Caring! ❤️