Monday, April 20, 2020

Input and Output in python program

Input and Output in Python
INPUT in a python program
Note:
1. Used to get data into the program
2. ‘input()’ function is used
3. Default return type of input() in string so has to be converted into desired format

 
Syntax:
input(<prompt_string_to _the user>)

Example:
val=input(“Enter the value:”)
print(val)

Input: Enter the value: 10
Output: 10
Data Type Conversion function that can be applied on string
Function
Example
Remarks
int()
val=int(input(“Enter the value”))
Converts string that has integer data into integer
float()
val=float((input(“Enter the value”))
Converts string that has Float data into float
list()
Ls=list(input(“Enter the list”))
The input list should be provided by comma separated values and its creates a list of string e.g. 1,2,3,4,5 -> [‘1’, ’2’, ’3’, ’4’, ’5’]
eval()
ILs=eval(input(“Enter the list”))
Eval function takes a coma separated values and convert it into a tuple of liste.g. 1,2,3,4,5  ->  (1,2,3,4,5)

 OUTPUT in a python program
Note:
1. print() function can be used to put data on a standard output device(monitor) or a file
2. print() function return None
Syntax of print() function:

print(*object , sep=‘ ’, end=’\n’, file=sys.stdout, flush=False)

Description of the arguments of the print function
1. *object - variable length argument I.e n number of any object(I.e list, integer etc) can be passed to the print function
2. sep - this argument is used in between values and the default value is space
3. end - this argument adds an end character after all the character are printed and by default its newline (\n) character  
4. file - this argument denotes the object where the values are to printed and by default its stdout(I.e Monitor)
5. flush - this argument basically closes the stream of character and empties the buffer

Example
Output
Remarks
print(‘Hello there’)
Hello there

print('2','+','3','is',2+3)
2 + 3 is 5
It also allows operation
print(1, 2, 3, 4, sep='*')
1*2*3*4
Replaces the separator with *
print(1, 2, 3, 4, sep='#', end='&')
1#2#3#4&
Adds & to the end of the string

 Formatting Output
Note: str.format() can be used to make the output look better

Example:
x=10
y=20
print(‘The value of x is  { } and y is  { } ’.format(x,y))

Output:
The value of x is 10 and value of y is 20

Resources:
2. Python docs
Share: