0% found this document useful (0 votes)
1 views

Inputs and Outputs

The document discusses the concepts of input and output in Python, explaining how to provide data to a computer and retrieve results. It covers various output statements, particularly the print() function, including formatting options and how to display variables and strings. Additionally, it describes input statements for accepting user input through the input() function and converting it to different data types.

Uploaded by

Ranveer Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Inputs and Outputs

The document discusses the concepts of input and output in Python, explaining how to provide data to a computer and retrieve results. It covers various output statements, particularly the print() function, including formatting options and how to display variables and strings. Additionally, it describes input statements for accepting user input through the input() function and converting it to different data types.

Uploaded by

Ranveer Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER

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

the output, as shown in


that a computer takes input, processes that input and produces
Figure 5.1:

Process the Input


Input Output
using some logic

Figure 5.l: Processing Input by the Computer

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

The print() Statement to the next linee. it


will throw the
cursor

function is called simply, it


When the print()
m e a n s that a blank
line will be displayed.

The print("'string ) Statement to the print() function,


characters. When a string is passed
A string represents group of
a
the example
the is displayed a s it is. See
string
print("Hello")
Hello
and single quotes have the same
that in case of strings, double quotes
Please remember
and hence can be used interchangeably.
meaning
print'Hello')
Hello
characters inside the function. An escape sequence is
print{)
We escape sequence
can use

special meaning. For example, "\n' indicates new line. \t


a character that contains a
represents tab space.

print("This is the \nfirst 1ine"


This is the
first 1ine

print"This is the Jtfirst 1ine")


This is the first 1ine
betore
To escape the effect of escape sequence, we ' (backslash)
should add one more

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.

The print(variables list) Statement


We can also display the values of variables using the print) function. A list of variables
can be supplied to the print(0 function as:
a, b 2, 4
print(a)
2

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

'end'attribute. The way one can use it is end="characters" which


characters for the line. indicates the
will be " Suppose, we write end=", then the ending character for endina
display the next output in the same line. See 1line
(nothing) and hence it will each
example: the
print("Hello" end)
print("Dear" , end=' ')
print' HoW are U?, end=" ")
Output:
HelloDearHow are U?
If we use
end='"\t' then the output will be displayed in the same line but tab space
separate themn as: will

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

The print(object) Statement


We can
pass objects like lists,
elements of those objects. For tuples
or dictionaries
to the print() function
example, to display the
1st =[10, 'A', Hai']
print(1st)
[10, 'A', 'Hai']
d {'Idly' :30.00, 'Roti':45.00,
rint (d
'Idly': 30.0, 'Roti': 45.0, 'chappati:55.50}
'Chappati'55.5}
The print("string, variables
list) Statement
The most common of use the
the print() function.
print() function is to use
strings along with variables inside
a=2
print(a, "is even
2 is even number number")
print(You typed,
You typed 2 as 1nputa,
'as input')

The print(formatted string) Statement


The output displayed by the print) function can be
formatted as we like. The spe
ecial

onerator %' (percent) can be used for this or


purpose. It joins a string with a e
value in the following format: variab
Input and Output 99

printC"formatted string" % (variables 1ist))


In the "formatted string'", we can use %i or %d to represent decimal integer numbers. We
can use %f to represent float values. Similarly, we can use %s to represent strings. See
the example below
X=10
print('value= %i' % x)
value= 10

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

print('Hai -20s)% name


Hai (Linda
We can use %c to display a single character as shown below:
name-"Linda
print('Hai%c,% % (name[O01 namef11))
Hai L, 1
The above example displayed 0th and 1st characters from name variable. We can use
slicing operator on a string to display required characters from the string. For example,
name[0:21 gives 0th to 1st characters from name as:
print('Hai %s' %(name [0:21))
Hai Li
To display floating point vallues, we can use %f in the formatted string. If we use %8.2f,
then the float value is displayed in 8 spaces and within these spaces, a decimal point and
next 2 fraction digits.

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

order of the values.


After the formatted strina . These
the
n a m e s o r indexes
represent w e should mention the

Write member operator


and then format() method where values to
format given below:
be displayed. Consider the general
with replacement
fields.format (values))
print('format string
field, we c a n write as:
value using index in the replacement
To display a single
n1, n2, n3,=1, 3E. (n1))
printC'number1-{0}'.format
number1=1

which replaced by the value of n1. To displavall


In the above statement, observe {0} was

the three numbers, we can use:

print(number1-{0}, number2-{1}, number3-123format (n1, n2, n3))


numberl=1, number2=2, number3-3
In the above statement, {0}, {1}, {2} represent the values of n1, n2 and n3, respectively
Hence, if we change the order of these fields, we wil have order of the values to be
changed in the output as:
printC'number1-11}, number2-101, number3-{23".format(n1, n2, n3))
number1=2, number2-1, number3=3
As an alternate, we can also use names in the replacement fields. But the values for
these names should be provided in the format() method. Consider the following example:

print'number1={two3, number2-fone}, number3-{three}'.format(one=nl,


two=n2, three=n3))
number1=2, number2-1, number3-3
We can also use the curly braces without mentioning indexes or names. In this case,
those braces will assume the sequence of values as they are given. Consider the following
statements:

print(' number1-={}, number2-{}, number3-{} format (n1, n2, n3))


numberl=1, number2=2, number3=3
All the four examples given below will display the same output:
name, salary Ravi', 12500.75
print('Hello
Hello
{O}, your salary is {l}.format (name, salary))
Ravi, your salary is 12500.7.
print("
Hello
Hello {n}, your salary is {s}'.format (n=name, S=salary))
Ravi, your salary is 12500.75
print('Hello {:s}, your salary is {:.2f}'.format (name, salary))
Hello Ravi, your salary is 12500.75

print('Hello %s, your salary is %.2f' % (name, salary))


Hello Ravi, your salary is 12500.75
Input and Output 101

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:
=

Enter your name: Raj kumar

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

keyboard is also same a s accepting a string TL:


This
The way we accept a character from the
is shown in Program 2.

Phonam
Program 2: A Python program to accept a character as a string.

# accepting a single character or string from keyboard


ch = input("Enter a char: ")
print("U entered: "+ch)
Output:
C:python Input.py
Enter a char: A
U entered: A

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

x = int(str) #convert string into int


print(U entered: , X); #display the int number
Output:
C:\>python Input.py
Enter a number: 88778
U entered: 887778
The same program can be rewritten by combining the first two statements, as shown in
Program 5.

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.

# accepting two numbers from keyboard


x = int(input('Enter first number:
Y = int(inputCEnter second number: ')
print('u entered: ', x, y) #display both the numbers separating wi th a space
104 Chapter 5

Output:
C:\python Input.py
Enter first number: 12
Enter second number: 45
U entered: 12 45

numbers in the output are displayed using a space. Suppose we want to i .


to displa
The two
these numbers using a comma as separator, then we can use sep=, in thee
t
function as:
print'U entered: ', x, y, sep=",');
In this case, the output will be:

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

prit (The sum of O} and (1 is 2} and product of 10} and {1} is


{33format(X,Y,X+y,X*y))
Output:
C: >python Input.py
Enter first number: 45
Enter second number: 65
The sum of 45 _and 65 is 110
The product of 45 and 65 is 2925
The sum of 45 and 65 is 110 and product of 45 and 65 is 2925
In Program 10, we accept numbers in hexadecimal, octal and binary systems and display
their equivalent decimal numbers.

Paoam
PrograNO:A Python program to convert numbers from other systems into decimal
number system.

# input from other number systems


str input('Enter hexadecimaT number: #accept input as string
n int(str 16)#inform the number is base 16
printHexadecimal to Decimal n)
strinput(Enter octal number: )
n int (str, 8) # inform the number is base 8
printOctal to Decimal-, n);
str inputC'Enter binary number: ')
n int(str, 2) #inform the number is base 2
print(Binary to Decimal n);
Output:
C:>python convert.py
Enter hexadecimal number: a
Hexadecimal to Decimal= 10
Enter octal number: 10
Octal to Decimal 8
Enter binary number: 1101
Binary to Decimal= 13
o accept more than one input in the same line, we can use a for loop along with the
input() function in the following format:
a, b [int(x) for x in input("Enter two numbers: ").split(0]
In the previous statement, the input) function will display the message Enter two

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

in the same line


line and display
Poegram program
to accept
3 integers
ther
Program 11:
A Python
sum.
by space
numbers separated in input("Enter three numhane.
#accepting 3
varl, var2, var3
print('sum =
=
for x
[int(x)
varl+var2+var3)
").split0
Output
C:>python Input.py
Enter three numbers: 10 20 30
Sum=60

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

Program 13: A Python program to accept a group of strings separated by comma


display them again.

#accepting a group of strings from keyboard.


Ist x for x in input(CEnter strings: ').split(,'2]
print( You entered: \n
Output:
C:\>python Input.py
Enter strings: Anil, Vijay Kumar, Priya
You entered:
'Ani1', 'vijay Kumar', 'Priya'] ,
ae function takes a string and evaluates the result
eval0 of the string by taking it as a
ion. For example, let's take a string: "atb-4"
Python expression where a =
5 and b =10. If we
pas
sthe string to the eval() function, it will evaluate the string and returns the result.
Consider the following example:

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

Paoan accept n tuplc and display it.


Program 16: A Python progrnm to

accepting a tuple from keyboard


eval(input("Enter a tuple: "))
tpl
printC"Tuple ", tp1)

Output
C:\>python Input.py
Enter a tuple: (10, 20, 30, 40)
20, 30, 40)
Tuple (10,

Command Line Arguments


a way that we can pass inputs to the program wh
when
We can design our programs in such
For example, w e write a program by
run command.
the name
'add.py that takes
we give as input to the program a
the two numbers
two numbers and adds them. We can supply
command prompt a s :
the time of running the program at

C:pythonadd.py 10 22
Sum 22

Python name. While running this program, we are passing


Here, add.py is our program
two arguments 10 and 22 to the program, which are called command line arguments. So,
at command
command line arguments are the values passed to a Python program
a r e passed to the program from
prompt (or system prompt). Command line arguments
outside the program. All the arguments should be entered from the keyboard separating
default in the form of strings in a list
them by space. These arguments a r e stored by
a
contains al
with the n a m e 'argv' which is available in sys module. Since argv is a list that
the values passed to the program, argv[0] represents the name of the program, argvl
"
represents the first value, argv|2] represents the second value and so on, as shown
Figure 5.2:

C:P python add.py 10 22

argv add.py '10 | 22


argv[o] argv[1] argv[2]
Figure 5.2: Command Iine args are stored as strings in argy list
n c t i o n /

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.

# to display command Tine args. Save this as cmd.py.


import sys
n len(sys.argv) #n is the number of
arguments
args sys.argv #args list contains arguments
print( No. of command 1ine args= ', n)
print(The args are:, args)
printCThe args one by one: 1)
for a in args:
print(a)
Output:
C:>python cmd.pY 10 Aishwarya Rai 22500.75
NO. ofcommand line args= 5
The args are:['cmd.py',10', Aishwarya", Rai', '22500.75']1
The args one by one:
cmd.py
10
Aishwarya
Rai
22500.75
Observe the output of the Program 17. Actually, we are passing 3 arguments: 10,
Aishwarya Rai and 22500.75. But they are stored as 4 arguments as we can see in the
output. The reason is the string 'Aishwarya Rai' has two words and hence it is taken as
two arguments instead of
one. So, how to make
Aishwarya Rai' as a single argument?
For this purpose, we should enclose this string within quotation marks in either of the
two ways shown below:

"Aishwarya Rai" #double quotes inide Sing1e quotes


"AishwaryaRai # Single quotes inside doube quotes
Let's run the Program 17 again and see the output.
C:python cmd.py 10"'Ai shwarya Rai" 22500.75
No. of command 1ine args=
The args are: ['cmd.py 10 Aishwarya Rai'" 22500.75']
The args one by one:
Cmd.py
10
'Ai shwarya Rai
22500.75
in
Program 18, we are accepting two numbers from command line and
ne logic is finding their sum.
straight forward. We know that all the command line arguments are stored
by
erault in
argv. So, argv[0] represents our program name. argvl1] represents the first
mber and argv|2] represents the second number entered at command prompt. Since
y detault, all command line arguments are stored in the form of strings, we can convert
Lnem into
numeric format using int() float() functions as:
or

int(sys.argv[1]) # Converts argv[1] into int type


Tloat(sys.argv[2J) # Converts
argv[2] into float type
110 Chapter 5

numbers, we can periorm any arithmetin


Once the arguments are available as
on them.
operations
Pogram 18: A Python program to find sum of two numbers using
command lin
com

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

numbers. This is shown in Program 19.

PPanam of numbers using command line


Program 19: A Python program to find the sum even

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

print('Sum of evens= Sum)


Output:
CPython cmd.py
'9'
6 8 9 10 11
Sum of evens= 24
10' '11'1
Python programs using commana line arguments should be executed only at the
command prompt as shown in the previous sections. They cannot be executed in Python

IDLE, as it does not support passing the arguments at runtime.

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:

print 'number1=, number2=8, number3=0'. format(n1, n2, n3))


a Another important format of the print() function is to use with format strings like %d,
%c, %s as:

print(Hello %s, your salary is %.2f % (name, salary))

Python provides the input) function that accepts data or input from the keyboard.
The general format of input) function is this:

str input(Enter a string: )

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:

a, b [int(x) for in input('Enter two numbers:


x
").split('separator)]
Command line arguments are the values passed to a Python program at command
prompt (or system prompt).
Command line arguments stored
by default in argvl| as a list.
are

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:]

The argparse module is useful to create user-friendly command line arguments


programs. The parser in the argparse module automatically generates help and usage
age
messages and error messages when user gives invalid arguments to the program.

You might also like