Inputs and Outputs
Inputs and Outputs
INPUT AND
OUTPUJT 5
results. It means that first
he purpose of a computer is to process data and return
the computer is
of all, we should provide data to the computer. The data given to
called input. The results returned by the computer are called output. So, we can say
To provide input to a computer, Python provides some statements which are called Input
statements. Similarly, to display the output, there are Output statements available in
Python. We should use some logic to convert the input into output. This logic is
implemented in the form of several topics in subsequent chapters. We will discuss the
input and output statements in this chapter, but in the following order:
Output statements
Input statements
96 Chapter 5
Output statements
function, This function can be
car
the print()
results, Python providcs
To display output or
discusscd hereunder.
which are
used in different formats
scape sequence character. For example, \\n displays \n' and \\t displays "\t
print("this is the \\nfirst 1ine")
this is the \nfirst 1ine
We can use repetition operator (* ) to repeat the strings in the output as:
print (3*'Hai')
HaiHaiHai
4 will
The operator + when used on numbers will perform addition operation. The same
tions
not do addition operation on strings as it is not possible to perform arithmetic operauu
l e n c e
on strings. When we use + on strings, it will join one string with another string. He
+is called concatenation joining) operator when used on strings.
print("city
City name="+"Hyderabad")
name=Hyderabad erabad")
Input and Output 97
The+operator in the preceding statement joined the two strings without any space in
between. We can also write the preceding statement by separating the strings using ,
as
print("city name=", "Hyderabad")
City name= Hyderabad
In this case, a space is used by the print) function after each string. In the output,
observe the single space after the string City name=. When the print) function sees a
comma, it will assume that the values are different and hence a space should be used
between them for clarity.
print(a, b)
4
Observe that the values in the output are separated by a space by default. To separate
the output with a comma, we should use sep' attribute as shown below. 'sep' represents
separator. The format is sep="characters" which are used to separate the values in the
output.
print(a, b, sep-","
2,4
print(a, b, sep E
2:4
print(a, b, sep
2----4
When several print() functions are used to display output, each print) function will
display the output in a separate line as shown below:
printCHello")
print("Dear")
print('HoW are U?')
Output:
Hello
Dear
How are U?
ach print function throws the cursor into the next line after displaying the output. This
n e reason we got the output in 3 lines. We can ask the print) function not to throw
ne cursor into the next line but display the output in the same line. This is done using
98 Chapter 5
print("Hello", end='\t')
print"Dear",
print How are end='\t')
U?, end-'\t
Output:
Hello Dear
If we use
How are U? 322232a
end="\n' then the output is displayed in
value for 'end' attribute. a
separate line. So, '\n' is the default
As seen above, to display a single variable (i.e. x) , we need not wrap it inside
parentheses. When more than one variable is to be displayed, then parentheses are
needed as:
X, y 1 0 , 15
printC'x i y %d % (x, y))
X= 10 y= 15
To display a string, we can use %s in the formatted string. When we use %20s, it will
allot 20 spaces and the string is displayed right aligned in those spaces. To align the
string towards left side in the spaces, we can use %-20s. Consider the following
examples:
name=Linda'
print Hai %5 name
Hai Linda
print('Hai (%20s)%name)
Hai Linda
When we use %.3f, then the float value is displayed with 3 fraction digits after the
decimal point. However, the digits before decimal point will be displayed as they are.
Consider the following examples:
num=123.456789
print(The value is: %f % num)
The value is: 123.456789
print('The value is: %8.2f' %num)
100 Chapter 5
before the value
2 spaces
1 2 3 . 4 6 #observe
The value is: %num)
value is: %.2f"
print( The 123.46
The value is: field w n i c h is denoted hya
replacement
Inside the formatted string,
we c a n u s e
indexes in
these replacement fielPar of
curly braces{ }.
We c a n mention
names or
Input Statements
To accept input from keyboard, Python provides theinput) function. This function takes
a value from the keyboard and returns it as a string. For example,
str input() # thi_ wil1 wait til1 we enter a string
Raj kumar enter this string
print(str)
Raj kumar
It is a better idea to display a message to the user so that the user understands what to
enter. This can be done by writing a message inside the input) function as:
str input("Enter your name:
=
print (str)
Raj kumar
Once the value comes into the variable 'str', it can be converted into int' or float' etc.
This is useful to accept numbers as:
str=input( Enter a number:
Enter a number 125
x
int(str) Str is converted into int
print(x)
125
We can use the int() function before the input) function to accept an integer from the
keyboard as:
x = int(input ( Enter a number:
Enter a number: 125
print(X)
125
Similarly, to accept a float value from the keyboard, we can use the float() function along
with the input() function as:
x =
float (input('Enter a number:)
Enter a number 12.345
print(x)
12.345
We will understand these
concepts with the help of a Python program. Let's write a
program to accept a string and display it, as shown in Program 1.
Phoam
Frogram 1: A Python program to accept a string from keyboard and display it.
#accepting a string from keyboard
str = jnput("Enter a string:")
print'U entered:, str) #display entire string
102 Chapter 5
Output:
C:>python Input.py
Enter a string: Helllo
U entered: Hello
Phonam
Program 2: A Python program to accept a character as a string.
C:>python Input.py
Enter a char: abcd
U entered: abcd
From the output of the above program, we can
understand that the input() function is
accepting the character as a string only. If we need
only a
the index, as:
ch|[0]. Here 0th character is taken from character, then we should use
the string. This is shown in
Program 3.
Progam
Program 3: A
Python program to accept a single
character from
#accepting
ch input("a single character from
keyboard.
Enter a char: ") keyboard
printC"U entered: "+ch [0])
Output:
C:python
Enter a Input.py
U entered: a char: abcd
Now, let's plan a
input) unction program to accept an integer number
Hence, we shouldaccepts only a string, it will accept from the
keyboard. Sn e, the
convert
shown in Program 4. that string into the integer
integer number using number also as a
the int() function: seis is
***
Proyram 4:
Program A
Python program to
# accept an integer
accepting
str intejer from number from
keyboard.
input 'Enter a
=
keyboard
number:
Input and Output 103
Pronam
Program 5: A Python program to accept an integer number from keyboard version 2.
accepting integer
int(input(
number from keyboard v2.0
Enter a number:
print(u entered:,x) #display the int number
Output:
C:Ppython Input.py
Enter a number: 98798798423422
U entered: 98798798423422
The same procedure can be adopted to accept a floating point number from the keyboard.
While the input() function accepts a float value as a string, it should be converted into
float number using the float() function. This is shown in Program 6.
Pocoa
Program 6: A Python program to accept a float number from keyboard.
# accepting float number from keyboard
x float (input('Enter a number:
print('u entered: x ) #display the float number
Output:
C:>python Input.py
Enter a number: 9.123456789123456789
U entered: 9. 123456789123457
From the above output, we can understand that the float values are displayed to an
accuracy of 15 digits after decimal point. In the next program, we will accept two integer
numbers and display them.
Proram
Program 7: A Python program to accept two integer numbers from keyboard.
Output:
C:\python Input.py
Enter first number: 12
Enter second number: 45
U entered: 12 45
Uentered: ,12,45
Observe the commas after U entered:' and after 12. A betiter way to
display these
numbers separating them using commas is this:
printC'u entered: %d, «d' %x, y))
Let's write a Python program to numbers from keyboard and find their
accept two
sum.
This is shown in Program 8.
Proam
Program 8: A Python program to accept two numbers and find their sum.
#find sum of two numbers
x
int(input(Enter first
=
y = int(input'Enter secondnumber:
printThe sum of,X,
print'The sum
number:
of
and
{} and {} is
. ".
is
{}'.format
, X+y) #display sum
(x, y, x+y)) #display again
Output:
C:\>python Input.py
Enter first number: 88
Enter second number: 98
The sum of 88 and 98 is 186
The sum of 88 and 98 is 1865
Let's find the product of two given numbers. The previous program is improved to find
product of the numbers as shown in Program 9.
Pngkam
togranm 9: A
Python program to find sum and product of two numbers.
# find sum and product of two
numbers
int(input(" Enter first number:
int(input('Enter second number:
#display sum
print('The sum of {0} and {1} is
{2}'.format (x,y, x+y))
#display, product
print The product of {0} and {1} is {2}'.format
#display both sum and product (x, y x*y)) ,
Input and Output| 105
Paoam
PrograNO:A Python program to convert numbers from other systems into decimal
number system.
numbers: to the user. When the user values, they are accepted as strings.
enters two
hese strings are divided wherever a space is found by split) method. So, we get two
Strings as elements of a list. These strings are read by for loop and converted into
ntegers by the int() function. These integers are finally stored into a and b.
pt method by default splits the values where a space is found. Hence, while
cntering the numbers, the user should separate them using a space. The square
CKets[around the total expression indicates that the input is accepted as elements
106 Chapter 5
numbers from in + same
3 integer ne. While
how to accept them with
at least one space.
on.
11 shows separate
list. Program should
ofa numbers,
the user
entering
the
Suppose the user wants to separate the input with commas while entering them
specify a comma for the split() method as shown in Program 12.
Paoaa
Program 12: A Python program to accept 3 integers separated by commas and display
their sum.
#accepting 3 numbers separated by comma
var1, var2, var5Lint(X)TorX in inputEnter three numbers: ").
split')]
print'sum = var1+var2+var3)
Output:
C:Ppython Input.py
Enter three numbers: 10, 20,30
Sum 60
them
Now we will see how to accept a group of strings from the keyboard and display
again. We should remember that the input() function reads given data in the form o
strings. Hence the variable x' in Program 13 takes the strings one by one from the inpu
function.
Paegam and
a, b= 5, 10
result= eval("a+b-4")
print(result)
11
We can use the eval() function along with
input() function. Since the input() function
accepts a value in the form of a string, the eval( function receives that
string and
evaluates it. In Program 14, we can enter an expression that is evaluated
function and result is displayed.
by the eval0
Paoa
Program 14: Evaluating an
expression entered from keyboard.
#using eval) along with input) function
x eval (input( Enter an
=
express1on
printC"Result %d * % x) www
Output:
C:Ppython Input py
Enteranexpression: 10+54
Result 11
We the combination of eval() and
can use
input() functions to accept objects like lists or
tuples. When the user types the list using square braces [ ], eval() will understand that it
is a list, as shown in
Program 15:
Pron
Program 15: A Python program to accept a list and display it.
#accepting a 1ist from keyboard
Ist eval (input (" Enter a 1ist:)
print("List= st)
Output:
C: >python Input.py
Enter a list: ["Ajay","Preethi Sashank "Vishnu"]
List =['Ajay', "Preethi',"Sashank''vishnu1
C:python Input.py
Enter a_list: [10, 20, 30J
List =[10, 20, 30] ..
Sim
ly When the user types a tuple using parentheses ( ), eval() will understand that it
s a
tuple, as shown in Program 16.
108 Chapter 5
Output
C:\>python Input.py
Enter a tuple: (10, 20, 30, 40)
20, 30, 40)
Tuple (10,
C:pythonadd.py 10 22
Sum 22
If we want to find the number of command line arguments, we can use the len ed at
as: len(argv). The following program reads the command line arguments c
command prompt and displays them.
Input and Output 109
Phofaáen
Program 17: A Python program to display command linc arguments.
Program
arguments.
numbers. Save this as add.py
t o add two
import sys
#Convert args into integers and add them
sum =int(sys.argv[1})+int(sys.argvL2J)
printSum= , Sum))
Output:
C:\>python add.py 10 22
Sum= 22
enter some numbers and find the sum of even
even
We will write another program where we
arguments.
# to find sum of even numbers
import sys
# read command Tine arguments except the program name
args SySs.argv[1:
print(args)
sum=0
# find sum of even arguments .
for a in argS: ,
x= int (a) .
if x%2==0:
Sum+=X
Points to Remember
Python provides the print() function to display output o r results. We can use the
print) function with variables, strings and objects like lists, tuples and dictionaries.
The print() function with replacement fields and the format() method can be used as:
Python provides the input) function that accepts data or input from the keyboard.
The general format of input) function is this:
OThe input() function accepts every value as a string. We can use int() or float()
functions to convert this string into integer value or float value as:
x intinput('Entera number: ))
x float(input('Enter a number: ))
OTo accept more than one value in the line,
same we can use
input() function along
with split() method as:
argvl0] represents the program name, argv[1] represents the first command linne
argument, argv|2] represents the second command line
argument, and so on.
len(argv) gives the number of command line arguments.
116 Chapter 5
To read all command line arguments except 0th argument (1.e. the program name.
e, We
can use
args = Sys.argv|1:]