Py3 Type Conversion
Py3 Type Conversion
• Type conversion in the Python programming language, also known as data type
conversion, is a fundamental concept where one data type is converted into another.
Code:
num_int = 5 # Integer
num_float = 3.5 # Float
result = num_int + num_float # Implicit conversion
print("Result:", result)
print("Data type of result:", type(result))
Output:
Result: 8.5
Data type of result: <class 'float'>
Explicit Type Conversion In Python
num_string = '12'
num_integer = 23
# explicit type conversion
num_string = int(num_string)
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
OUTPUT:
Sum: 35
Data type of num_sum: <class 'int'>
Functions Used For Explicit Data Type Conversion In Python
Functio
Purpose Syntax / Example
n Name
num_str = "42“
int(a, Converts a string or number to an
num_int = int(num_str)
base) integer
Output: 42
num_str = "3.14”
Converts a value to a floating-point
float() num_float = float(num_str)
number
Output: 3.14
char = 'A‘
Converts a character to its Unicode
ord() unicode_value = ord(char)
integer value
Output: 65
num = 16
Converts an integer to a lowercase
hex() hex_string = hex(num)
hexadecimal string
Output: '0x10'
num = 8
Converts an integer to an octal
oct() oct_string = oct(num)
string
Output: '0o10'
list_data = [1, 2, 3]
tuple() Converts a sequence to a tuple tuple_data = tuple(list_data)
Output: (1, 2, 3)
Functions Used For Explicit Data Type Conversion In Python
4. Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
# To Swap the values of two variables using Addition and subtraction operator
P=P+Q
Q=P-Q
OUTPUT
P=P-Q
Please enter value for P: 13
Please enter value for Q: 43
print ("The Value of P after swapping: ", P)
The Value of P after swapping: 43
print ("The Value of Q after swapping: ", Q) The Value of Q after swapping: 13
Python program to swap two variables
# To Swap the values of two variables using multiplication and division operator
P=P*Q
OUTPUT
Q = P /Q
P=P/Q Please enter value for P: 13
Please enter value for Q: 43
The Value of P after swapping: 43
print ("The Value of P after swapping: ", P) The Value of Q after swapping: 13
print ("The Value of Q after swapping: ", Q)
Python program to swap two variables
P, Q = Q, P
OUTPUT
print ("The Value of P after swapping: ", P)
Please enter value for P: 13
print ("The Value of Q after swapping: ", Q) Please enter value for Q: 43
The Value of P after swapping: 43
The Value of Q after swapping: 13