7. Input and Output - 20 min read
- Why should we learn about input and output?
- Input
and output
- Convert
from string type into other types
- eval()
function
- Command
line arguments
- IndexError
- len()
function
- Programs
7. Input and Output
Why should we learn about input and output chapter?
- Till now we have hard-coded variable values and used to print those.
Program Hard coding the values
Name demo1.py
age=16
print(age)
output
16
|
- But in real time based on requirement few values, we should take at run time or dynamically.
This
way is good so, taking the values at run time is recommended than hard
coding.
Please enter the
age: 16
The entered value is:
16
|
Input and output
- Input represents data given to the program.
- Output represents the result of the program.
input()
- input() is a predefined function.
- This function accepts input from the keyboard.
- This function takes a
value from the keyboard and returns it as a string type.
- Based on requirement we can convert from string to other types.
Program Printing name by taking the value at run
time
Name demo2.py
name = input(“Enter the
name: ”)
print(“You entered the name as:
”, name)
Output
Enter the name: Nireekshan
Your entered the name as:
Nireekshan
|
Program Printing name and age by taking value
at run time
Name demo3.py
name = input(“Enter the name:
”)
age = input(“Enter the age:
”)
print(“You entered name as:
”, name)
print(“You entered age as:
”, age)
Output
Enter the name: Anushka
Enter the age: 60
Your entered name as: Anushka
Your entered age as: 60
|
Program Checking return type value for input() function
Name demo4.py
value = input(“Enter the
value ”)
print(“Your entered value
as: ”, value)
print(“type is: ”,
type(value))
Output:
C:\Users\Nireekshan\Desktop\Programs>py
demo4.py
Enter the value: Nireekshan
Your entered value as: Nireekshan
<class ‘str’>
C:\Users\Nireekshan\Desktop\Programs>py
demo4.py
Enter the value : 123
Your entered value
as: 123
type is: <class 'str'>
C:\Users\Nireekshan\Desktop\Programs>py
demo4.py
Enter the value : 123.456
Your entered value
as: 123.456
type is: <class 'str'>
|
Convert from string type into another type
- We can convert a string value into int, float, etc by using corresponding functions.
- From
string to int - int() function
- From string to float - float() function
Program Converting from string type to int type by using int()
function
Name demo5.py
age = input(“Enter
your age: ”)
print(“Your age is:
”, age)
print(“age type is:
”, type(age))
x = int(age)
print(“After
converting from string to int your age is: ”, x)
print(“now age type
is: ”, type(x))
C:\Users\Nireekshan\Desktop\Programs>py
demo5.py
Enter your age:16
age type is: <class 'str'>
Your age is: 16
After converting
from string to int your age is: 16
now age type
is: <class 'int'>
|
Program Converting from string to float type by using float()
function
Name demo6.py
salary =
input(“Enter your salary: ”)
print(“Your salary is:
”, salary)
print(“salary type
is: ”, type(salary))
x = float(salary)
print(“After
converting from string to float your salary is: ”, x)
print(“now salary type
is: ”, type(x))
Output
C:\Users\Nireekshan\Desktop\Programs>py
demo6.py
Enter your salary:12.34
salary type
is: <class 'str'>
Your salary is: 12.34
After converting
from string to float your salary is: 12.34
now salary type
is: <class 'float'>
|
Program Taking int value at run time.
Name demo7.py
age = input(“Enter
your age: ”)
x=int(age)
print(“Your age is:
”, x)
Output
Enter your age: 16
Your age is: 16
|
Program Taking int value at run time in a simple way
Name demo8.py
age =
int(input("Enter your age: "))
print("Your
age is: ", age)
Output
Enter your age: 16
Your age is: 16
|
Program Taking values at run time in simple way
Name demo9.py
age =
int(input("Enter your age: "))
salary = float(input("Enter
salary: "))
print("Your
age is: ", age)
print("Your salary
is: ", salary)
Output
Enter your age: 16
Enter salary: 123.456
Your age is: 16
Your salary is: 123.456
|
Program Accept two numbers and find their sum
Name demo10.py
x = int(input(“Enter first
number: “))
y = int(input(“Enter second
number: “))
print(“Sum of two values: “,
x+y)
Output
Enter first number:
10
Enter second
number: 20
Sum of two values:
30
|
Program Accept two numbers and find their sum
Name demo11.py
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("The sum of {} and {} is {}".format(x, y, (x+y)))
Output
Enter first number:
1
Enter second
number: 2
The sum of 1 and 2
is: 3
|
eval() function
- input() function returns string type.
- eval() is a predefined
function which takes a string as a parameter.
- If you entered any expression in the string, then eval() function evaluates the expression and returns the result.
Program eval() function evaluating expressions
Name demo12.py
print("10+20")
sum = eval("10+20")
print(sum)
Output
10+20
30
|
Program eval() function evaluating expressions
Name demo13.py
sum = eval(input("Enter expression: "))
print(sum)
output
Enter
expression: 2*3+4
10
|
Command line arguments
- While running a program we can provide the arguments.
- These provided
arguments are called Command line arguments.
- We need to use argv to
work with command line arguments.
- argv is a list in python.
- argv is available sys module.
- So, we need to import sys module to access argv.
Syntax:
- C:\Users\Nireekshan\Desktop\Programs>py demo.py 10 20
- argv[0] => Name of the program (demo.py)
- argv[1] => 10
- argv[2] => 20
Make a note:
- When providing arguments,
- The
first argument argv[0] is Name of the program.
- Remaining arguments are argv values respectively.
Program Printing run time arguments by using argv.
Name demo14.py
from sys import argv
print(argv[0])
print(argv[1])
print(argv[2])
Run python demo14.py 30 40
Output
demo14.py
30
40
|
IndexError
- If we are trying to access command line arguments with out of range index, then we will get IndexError.
Program Accessing index which is out of range.
Name demo15.py
from sys import argv
print(argv[100])
Run python demo15.py 30 40
Output
IndexError: list index out of range
|
Program Without command line arguments addition
Name demo16.py
x = 10
y = 20
print(x+y)
Output
30
|
Make a note
- Command line arguments are string type, means argv returns string type,
- So, by default argv
type is a string.
- Based on the requirement we can convert from string type to another type.
Program Checking argv type
Name demo17.py
from sys import argv
first_name = argv[1]
last_name=argv[2]
print(“First name is: ”, first_name)
print(“Last name is: ”, last_name)
print(“Type of first name is”, type(first_name))
print(“Type of last name is”, type(last_name))
Run py demo17.py nireekshan subbamma
output
First name is: nireekshan
Last name is: subbamma
Type of first name is <class 'str'>
Type of last name is <class 'str'>
|
Program Adding items costs which is in sting
type by using argv
Name demo18.py
from sys import argv
item1_cost = argv[1]
item2_cost =argv[2]
print(“First item cost is: ”, item1_cost)
print(“Second item cost is: ”, item2_cost)
print(“Type of item1_cost is : ”, type(item1_cost))
print(“Type of item2_cost is : ”,
type(item2_cost))
total_items_cost= item1_cost + item2_cost
print(“Total cost is: ”, total_items_cost)
Run py demo18.py 111 223
output
First item cost is: 111
Second item cost is: 223
Type of item1_cost is : <class 'str'>
Type of item1_cost is : <class 'str'>
Total cost is: 111223
|
- + operators join or concatenates two string values.
- If we are adding two
string values the by using + operators then joined string will be the output
- It’s possible to convert from string type to others by using corresponding pre-defined methods.
Program Adding items costs by using argv
Name demo19.py
from sys import argv
item1_cost = argv[1]
item2_cost = argv[2]
x=int(item1_cost)
y=int(item2_cost)
print("First item cost is: ", x)
print("Second item cost is: ", y)
print("Type of item1_cost is : ",
type(x))
print("Type of item2_cost is : ",
type(y))
total_items_cost= x + y
print("Total cost is: ",
total_items_cost)
Run py demo19.py 111 223
output
First item cost is: 111
Second item cost is: 223
Type of item1_cost is : <class 'int'>
Type of item2_cost is : <class 'int'>
Total cost is: 334
|
len() function
- len() is a predefined function which returns the number of values
Program print command line arguments to find
length
Name demo20.py
from sys import argv
print(“The length of values :”,
len(argv))
Run python demo20.py 10
20
Output
The length of
values :3
|
Program print command line arguments one by one
Name demo21.py
from sys import argv
print(“Total arguments: ”, argv)
print(“Command Line Arguments one by
one:”)
for x in argv:
print(x)
Run
python demo21.py nireekshan subbamma
Output
Total arguments: [‘demo21.py', 'nireekshan', ' subbamma']
Command Line Arguments one by one:
demo21.py
nireekshan
subbamma
|
Make a note
- By default, space is separator between command line arguments.
- While providing the values in command line arguments, if you want to provide space then we need to enclose with double quotes (but not single quotes).
Program passing text with spaces to command line arguments
Name demo22.py
from sys import argv
print(argv[1])
Run python demo22.py hello good
morning
Output
hello
|
Program double quotes string in a command line
arguments
Name demo23.py
from sys import argv
print(argv[1])
Run python demo23.py “hello good
morning”
Output
hello good morning
|
Program Text with spaces by using single quotes in command line
arguments
Name demo24.py
from sys import argv
print(argv[1])
Run python demo24.py ‘hello good
morning’
Output
‘hello
|
Q) How to extract only integer values from
command line arguments?
Answer:
- Please follow below programs carefully
Program Printing
command line arguments
Name demo25.py
from sys import argv
print(argv)
Run py demo25.py 111 222
['demo25.py', '111', '222']
|
Program Printing
one by one values from command line arguments
Name demo26.py
from sys import argv
for x in argv:
print(argv)
Run py demo26.py 111 222
Output
demo26.py
111
222
|
Program Printing
only integer values from the command prompt
Name demo27.py
from sys import argv
for x in argv:
if x.isdigit():
print(int(x))
Run py demo27.py 111 222
Output
111
222
|
Make
a note: isdigit()
- isdigit() is method in the string class.
- This
method check, Is value is a digit or not.
- If
it is a number then returns True otherwise False
- We will discuss more in String chapter
Program isdigit()
method in the string class
Name demo28.py
s = 'abc'
print(s.isdigit())
Output
False
|
Program isdigit()
method in the string class
Name demo29.py
s = '123'
print(s.isdigit())
Output
True
|
Program Printing the only integer from a command prompt and adding to list
Name demo30.py
from sys import argv
l = []
for x in argv:
if x.isdigit():
l.append(int(x))
print(l)
Run py demo30.py 111 222
Output
[111, 222]
|
Make
a note: append()
- append() is a method in the list data structure.
- This
method adds or appends an element to list.
- We will discuss more in list data structure chapter
Program Printing the only integer from command prompt apply an operation
Name demo31.py
from sys import argv
l = []
for x in argv:
if x.isdigit():
l.append(int(x))
print(sum(l))
Run py demo31.py 111 222
Output
333
|
Make
a note: sum()
- sum() is a predefined function, it returns the sum of all values