Posted in

Python Type Casting (Part 1): What is Type Casting or Type Conversion in Python?

Python Type Casting Part 1
Python Type Casting Part 1

Python Type Casting

Use of Python Type Casting

Code:
a = 'Python'
b = 104
print(a + b)

Output:
TypeError: can only concatenate str (not "int") to str

How Many Types of Python Type Casting?

1. Implicit casting or automatic casting
2. Explicit casting or manual casting or coercion type conversion

Implicit Casting in Python

Code:
a = 10      
b = 20.0    
c = a + b
print(c)
print(type(c))

Output:
30.0
<class 'float'>
Code:
a = 10
b = 20.0
c = a * b
print(c)
print(type(c))

Output:
200.0
<class 'float'>
Code:
a = True
b = 1
c = a + b
print(c)
print(type(c))

Output:
2
<class 'int'>
Code:
a = True
b = 15.0
c = a + b
print(c)
print(type(c))

Output:
16.0
<class 'float'>

Click to learn about Python data types

Explicit Casting in Python

Built-in FunctionsUses
int() functionUsed to convert into an integer data type.
float() functionUsed to convert into a float data type.
complex() functionUsed to convert into a complex data type.
str() functionUsed to converting into a string data type.
tuple() functionUsed to convert into a tuple data type.
list() functionUsed to convert into a list data type.
set() functionUsed to convert into a set data type.
dict() functionUsed to converting into a dictionary data type.
frozenset() functionUsed to convert a frozenset data type.
chr() functionUsed to convert a Unicode number into a character.
ord() functionUsed to converting a character into a Unicode number.

int() function in Python

Code:
num1 = 10
num2 = "10"
print(type(num1))
print(type(num2))
print(num1 + num2)

Output:
<class 'int'>
<class 'str'>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Code:
num1 = 10
num2 = int("10")
print(type(num1))
print(type(num2))
print(num1 + num2)

Output:
<class 'int'>
<class 'int'>
20
Code:
num1 = 10
num2 = int('Python')
print(num1 + num2)

Output:
ValueError: invalid literal for int() with base 10: 'Python'
Syntax: int(value, base)

value: First argument, here we provide a number or string that can be converted into an integer number.
base: This is an optional argument. Here we provide the number system in which we want to change the value. The default base value is 10. Base 10 means decimal number system.
Code:
num1 = int('50', 10)
Code:
num1 = int('100', 2)
Code:
num1 = int('100', 10)
num2 = int('100', 2)
print(num1)
print(num2)

Output:
100
4
Code:
num1 = 2.5 
print(type(num1))
print(num1)
num2 = int(num1)
print(type(num2))
print(num2)

Output:
<class 'float'>
2.5
<class 'int'>
2

End of the Python type casting (part 1)

Click for the Python type casting (part 2)

4 thoughts on “Python Type Casting (Part 1): What is Type Casting or Type Conversion in Python?

Leave a Reply

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