Python Typecasting
int() : converts string to integer.
#program to typecast user provided data to integer
age= input("Enter age in years : ")
print("age :",age,"and type(age) :",type(age))
age= int(age); #typecasting
print("after typecast\nage :",age,"and type(age) :",type(age))
#output
Enter age in years : 28
age : 28 and type(age) : <class 'str'>
after typecast
age : 28 and type(age) : <class 'int'>
Limitation:
to typecast user input data to integer, all provided data should be numbers, it should neither contains character nor '.' , it should be with base 10.
#output
case 1 :
Enter age in years : twenty Eight
age : twenty Eight and type(age) : <class 'str'>
Traceback (most recent call last):
File "C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 5, in <module>
age= int(age); #typecasting
ValueError: invalid literal for int() with base 10: 'twenty Eight'
Case 2:
Enter age in years : 28.6
age : 28.6 and type(age) : <class 'str'>
Traceback (most recent call last):
File "C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 5, in <module>
age= int(age); #typecasting
ValueError: invalid literal for int() with base 10: '28.6'
float() : converts string to float.
#program to typecast user provided data to float
mark= input("Enter mark in %: ")
print("mark :",mark,"and type(mark) :",type(mark))
mark= float(mark);
print("after typecast\nmark :",mark,"and type(mark) :",type(mark))
#output
mark= input(“Enter mark in %: ”)
print(“mark :”,mark,”and type(mark) :”,type(mark))
mark= float(mark);
print(“after typecast\nmark :”,mark,”and type(mark) :”,type(mark))
Limitation :
#program to typecast user provided data to integer
mark= input("Enter mark in %: ")
print("mark :",mark,"and type(mark) :",type(mark))
mark= float(mark);
print("after typecast\nmark :",mark,"and type(mark) :",type(mark))
#output
Enter mark in %: eighty.seven two
mark : eighty.seven two and type(mark) : <class 'str'>
Traceback (most recent call last):
File "C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 5, in <module>
mark= float(mark);
ValueError: could not convert string to float: 'eighty.seven two'
to typecast user input to float, all provided data should be numbers and should not contain characters
Other way of doing typecasting
we can typecast data at the time of collection itself.
#program to typecast user provided data
age= int(input("Enter age in years : "))
mark= float(input("Enter mark in %: "))
print("age :",age,"and type(age) :",type(age))
print("mark :",mark,"and type(mark) :",type(mark))
#output
Enter age in years : 28
Enter mark in %: 80.72
age : 28 and type(age) : <class 'int'>
mark : 80.72 and type(mark) : <class 'float'>
Comments
Post a Comment