Type conversion functions
Type conversion functions are used to convert one type of value to another
type.
1. Int()
2. Float()
3. Complex()
4. Bool()
5. Str()
int()
This function is used to perform the following conversions.
1. Int to int
2. Float to int
3. String to int
4. Bool to int
Syntax-1: int(value)
Syntax-2: int(value,base=10)
Syntax-1 is used to convert int,float,bool to int type.
Syntax-2 is used to convert string to int type
Example:
>>> s1="45"
>>> s2="70"
>>> s1+s2
'4570'
>>> int(s1)+int(s2)
115
>>> n1=int(s1)
>>> n2=int(s2)
>>> print(n1,n2,type(n1),type(n2))
45 70 <class 'int'> <class 'int'>
>>> n3=int(s1,base=8)
>>> print(n3)
37
>>> print(oct(n3))
0o45
>>> n4=int(s1,base=16)
>>> print(n4)
69
>>> print(hex(n4))
0x45
>>> s1="101"
>>> n1=int(s1)
>>> print(n1)
101
>>> n2=int(s1,base=2)
print(n2)
5
>>> print(bin(n2))
0b101
>>> s1="101"
>>> s2="100"
>>> int(s1)+int(s2)
201
>>> int(s1,base=2)+int(s2,base=2)
9
>>> print(bin(9))
0b1001
>>> int(s1,base=8)+int(s2,base=8)
129
>>> print(oct(129))
0o201
Example:
# write a program to input two integers and print sum
a=input("Enter First Number")
b=input("Enter Second Number")
c=int(a)+int(b)
print(a,b,c,sep="\n")
Output:
Enter First Number5
Enter Second Number4
5
4
9
Example:
# Write a program to input integers and swap it
n1=int(input("Enter First Integer "))
n2=int(input("Enter Second Integer "))
print("Before Swaping ",n1,n2)
#Method1
n3=n1
n1=n2
n2=n3
print("After Swaping ",n1,n2)
#Method2
n1,n2=n2,n1
print("After Swaping ",n1,n2)
#Method3
n1=n1+n2
n2=n1-n2
n1=n1-n2
print("After Swapping ",n1,n2)
Output:
Enter First Integer 10
Enter Second Integer 20
Before Swaping 10 20
After Swaping 20 10
After Swaping 10 20
After Swapping 20 10
Example:
# Write a program to input name and 2 subject marks
# and calcualte total marks
name=input("Enter Name ")
sub1=int(input("Enter Subject1 Marks "))
sub2=int(input("Enter Subject2 Marks "))
tot=sub1+sub2
print(name,sub1,sub2,tot)
Output:
Enter Name naresh
Enter Subject1 Marks 90
Enter Subject2 Marks 90
naresh 90 90 180
float() function
This conversion function performs the following operations
1. Int to float
2. Float to float
3. String to float
4. Bool to float
Syntax: float(value)
>>> f1=float(1.5)
>>> f2=float("1.5")
>>> f3=float("1.5e-1")
>>> f5=float(True)
>>> f6=float(False)
>>> f7=float(5)
>>> f8=float("5")
>>> print(f1,f2,f3,f5,f6,f7,f8)
1.5 1.5 0.15 1.0 0.0 5.0 5.0
Example
# Write a program to find area of circle
r=float(input("Enter R Value"))
area=3.147*r*r
print("Area of Circle is ",area)
Output:
Enter R Value1.2
Area of Circle is 4.53168
complex()