
Python: Input and Output statements
Input Statements: Reading dynamic data from keyboard
Python 2: In Python 2, two functions are available for input:
-
raw.input()
-
input()
​X=raw.input(‘enter some number’)
Whatever input we provide, it is always treated as str type only. Hence you have to use typecasting functions.
​Y=input(‘Enter some number’)
No need to use type casting functions as it takes the input as it is.
Python 3: In Python 3 only one function is available that is input().
X=input(‘Enter some number:’)

Input function is always considered as string. Hence you have to use typecasting functions.
​
Example 1: Write a program to read two numbers from keyboard and print their sum.


Example 2: Write a program to read employee data from keyboard and print it.


If you want to take multiple input in one line


Example 3: Read 2 float values from the keyboard which are specified with separation and print sum


eval(): eval function prints type of data entered. If we enter integer data, then output from eval function will be 'int' and likewise.


Command Line Arguments
The argument which are passing from command prompt are called command line argument.
For example py test.py 10 20 30 40 50 (command line argument)
​
argv:
-
Predefined variable
-
Internally it holds all command line value
-
It is list type and available in sys module.
If you want to use argv from sys module, then you have to import it.
Example:


Example: Read a group of int values from the keyboard as command line arguments and print sum.


Output Statements
print () function is used to print some statement to the console.
​
Form 1: print() without any argument
a new line or empty line character will be inserted.
​
Form 2: print(str) with string argument
print(“Hello”)
print(“mujtaba”)

Form 3: print() with variable number of arguments
Example:
a,b,c=10,20,30
print(“The values are:”,a,b,c)

Form 4: print with sep (separator) attribute
It is used to separate attribute by space or comma or colon within the attribute.
By default comma (,) is the separator between the attributes
Example:
print(a,b,c,sep=’:’)

Form 5: print() with end attribute
By default print is going to print in new line. If you don’t want to print in new line, you can go for end attribute.

Example:
print(“hello”,end=” ”)
print(“mujtaba”)

Form 6: print(object)

Form 7: print(string, variable list)
You can use print() statement with string and any number of arguments.
It is used to represent or mix up the variable.

Form 8: print(formatted string)
%i == > int type
%d == > int type
%f == > float type
% s == > str type
print(“formatted string” %(variable list))
​
Example:
a,b,c=10,20
print(“a value is %i and b value is %i” %(a,b))

Form 9: print() function with replacement operator
{} == > replacement operator
It is used to format the output in desired forms.
For example:
name=’Mujtaba’
age=1
Type 1

Type 2

Type 3
