We can read the data from keyboard by using following functions.
1. raw_input() - It reads the data from the keyboard in the form of string format.
Example -
x=raw_input('enter no : ')
print x
print type(x)
Output -
enter no : 10
10
<type 'str'>
Type conversion functions
These are used to convert one datatype represented data in the form of another datatype.
- int() - Converts the string represented data in the form of int format.
PROGRAM TO PERFORM ADDITION OF TWO NUMBERS BY READING THOSE NUMBERS FROM KEYBOARD USING raw_input()
i=raw_input('enter num1 : ');
j=raw_input('enter num2 : ');
print type(i)
print type(j)
print i+j
i=int(i)
print type(i)
print i
j=int(j)
print type(j)
print j
print i+j
Output -
enter num1 : 10
enter num2 : 20
<type 'str'>
<type 'str'>
1020
<type 'int'>
10
<type 'int'>
20
30
Shortcut - print int(raw_input('enter num1 : '))+int(raw_input('enter num2 : '))
- long() - It is used to convert the string represented data in the form of long data type format.
Example -
x=raw_input('enter longnum : ');
print type(x)
print x
y=long(x)
print type(y)
print y
Output -
enter longnum : 123456789012345
<type 'str'>
123456789012345
<type 'long'>
123456789012345
- float () - It is used to convert string represented data in the form of float datatype format.
Example -
x=raw_input('enter floatnum : ');
print type(x)
print x
y=float(x)
print type(y)
print y
Output -
enter floatnum : 123.123
<type 'str'>
123.123
<type 'float'>
123.123
- complex() - It is used to convert the string represented data in the form of complex datatype format.
Example -
x=raw_input('enter complexnum : ');
print type(x)
print x
y=complex(x)
print type(y)
print y
Output -
enter complexnum : 2+4j
<type 'str'>
2+4j
<type 'complex'>
(2+4j)
- bool() - It is used to convert the string represented data in the form of bool datatype format.
Example -
x=raw_input('enter bool : ');
print type(x)
print x
y=bool(x)
print type(y)
print y
Output -
enter bool : TRUE
<type 'str'>
TRUE
<type 'bool'>
True
2. input() - It is used to read data from keyboard directly in our required format.
Example -
i=input('Enter int no ')
print type(i)
print i
j=input('Enter long no ')
print type(j)
print j
k=input('Enter float no ')
print type(k)
print k
x=input('Enter complex no ')
print type(x)
print x
y=input('Enter bool no ')
print type(y)
print y
Output -
Enter int no 123
<type 'int'>
123
Enter long no 12345678901234
<type 'long'>
12345678901234
Enter float no 123.123
<type 'float'>
123.123
Enter complex no 5+4j
<type 'complex'>
(5+4j)
Enter bool no True
<type 'bool'>
True
No comments:
Post a Comment