Chapter 7 Console Input/Output¶
Keynote¶
7.1 Console Input/Output¶
Console Input/Output means input from keyboard and output to screen.
7.2 Console Input¶
Console input can be received using the built-in input( ) function.
General form of input( ) function is s = input('prompt')
- prompt is a string that is displayed on the screen, soliciting a value. input( ) returns a string. If 123 is entered as input, '123' is returned.
# receive full name
name = input('Enter full name')
# separate first name, middle name and surname
fname, mname, lname = input('Enter full name: ').split( )
split( ) function will split the entered fullname with space as a delimiter. The split values will then be assigned to fname, mname, lname.
If we are to receive multiple int values, we can receive them as strings and then convert them to ints.
n1, n2, n3 = input('Enter three values: ').split( )
n1, n2, n3 = int(n1), int(n2), int(n3)
print(n1 + 10, n2 + 20, n3 + 30)
The same thing can be done using in a more compact manner using a feature called list comprehension. It applies int( ) function to every element of the list returned by the split( ) function.
n1, n2, n3 = [int(n) for n in input('Enter three values: ').split( )]
print(n1 + 10, n2 + 20, n3 + 30)
input( ) can be used to receive arbitrary number of values.
numbers = [int(x) for x in input('Enter values: ').split( )]
for n in numbers :
print(n + 10)
input( ) can be used to receive different types of values at a time.
data = input('Enter name, age, salary: ').split( )
name = data[0]
age = int(data[1])
salary = float(data[2])
print(name, age, salary)
7.3 Console Output¶
- Built-in function
print( )is used to send output to screen.
print( ) function has this form:
- This means that by default objects will be printed on screen (sys.stdout), separated by space
(sep = ' ')and last printed object will be followed by a newline (end = '\n').flush = Falseindicates that output stream will not be flushed.
Python has a facility to call functions and pass keyword-based values as arguments. So while calling print( ) we can pass specific values for sep and end. In this case, default values will not be used; instead the values that we pass will be used.
print(a, b, c, sep = ',', end = '!') # prints ',' after each value, ! at end
print(x, y, sep = '...', end = '#') # prints '...' after each value, # at end
7.4 Formatted Printing¶
There are 4 ways to control the formatting of output:
- a. Using formatted string literals - easiest
- b. Using the format( ) method - older
- c. C printf( ) style - legacy
- d. Using slicing and concatenation operation - difficult
Today (a) is most dominantly used method followed by (b).
r, l, b = 1.5678, 10.5, 12.66
print(f'radius = {r}')
print(f'length = {l} breadth = {b} radius = {r}')
name = 'Sushant Ajay Raje'
for n in name.split( ) :
print(f'{n:10}') # print in 10 columns
r, l, b = 1.5678, 10.5, 12.66
name, age, salary = 'Rakshita', 30, 53000.55
# print in order by position of variables using empty {}
print('radius = {} length = {} breadth ={}'.format(r, l, b))
print('name = {} age = {} salary = {}'.format(name, age, salary))
# print in any desired order
print('radius = {2} length = {1} breadth ={0}'.format(r, l, b))
print('age={1} salary={2} name={0}'.format(name, age, salary))
# print name in 15 columns, salary in 10 columns
print('name = {0:15} salary = {1:10}'.format(name, salary))
# print radius in 10 columns, with 2 digits after decimal point
print('radius = {0:10.2f}'.format(r))
- On execution, the above code snippet will produce the following output:
Problems¶
Problem 7.1¶
Write a program to receive radius of a circle, and length and breadth of a rectangle in one call to input( ). Calculate and print the circumference of circle and perimeter of rectangle.
Program
Tips
input( )returns a string, so it is necessary to convert it into int or float suitably, before performing arithmetic operations.
Problem 7.2¶
Write a program to receive 3 integers using one call to input( ). The three integers signify starting value, ending value and step value for a range. The program should use these values to print the number, its square and its cube, all properly right-aligned. Also output the same values left-aligned.
Program
start, end, step = input('Enter start, end, step values: ').split( )
# right aligned printing
for n in range(int(start), int(end), int(step)) :
print(f'{n:>5}{n**2:>7}{n**3:>8}')
print( )
# left aligned printing
for n in range(int(start), int(end), int(step)) :
print('{0:<5}{1:<7}{2:<8}'.format(n, n ** 2, n ** 3))
Output
Tips
{n:>5}will print n right-justified within 5 columns. Use<to left-justify.{0:<5}will left-justify 0th parameter in the list within 5 columns. Use>to right-justify.
Problem 7.3¶
Write a program to maintain names and cell numbers of 4 persons and then print them systematically in a tabular form.
Program
Problem 7.4¶
Suppose there are 5 variables in a programβmax, min, mean, sd and var, having some suitable values. Write a program to print these variables properly aligned using multiple fstrings, but one call to print( ).
Program
Problem 7.5¶
Write a program that prints square root and cube root of numbers from 1 to 10, up to 3 decimal places. Ensure that the output is displayed in separate lines, with number center-justified and square and cube roots, right-justified.
Program
Output
Exercises¶
[A] Attempt the following questions:¶
a. How will you make the following code more compact?
b. How will you print "Rendezvous" in a line and retain the cursor in the same line in which the output has been printed?
c. What will be the output of the following code snippet?
d. In the following statement what do > 5, > 7 and > 8 signify?
e. What will be the output of the following code segment?
f. How will you print the output of the following code segment using fstring?
g. How will you receive arbitrary number of floats from keyboard?
h. What changes should be made in
print(f'{'\nx = ':4}{x:>10}{'\ny = ':4}{y:>10}')
to produce the output given below:
x = 14.99
y = 114.39
i. How will you receive a boolean value as input?
j. How will you receive a complex number as input?
k. How will you display price in 10 columns with 4 places beyond decimal points? Assume value of price to be 1.5567894.
l. Write a program to receive an arbitrary number of floats using one input( ) statement. Calculate the average of floats received.
m. Write a program to receive the following using one input( ) statement.
Name of the person
Years of service
Diwali bonus received
Calculate and print the agreement deduction as per the following
formula:
deduction = 2 * years of service + bonus * 5.5 / 100
n. Which import statement should be added to use the built-in functions input( ) and print( )?
o. Is the following statement correct?
p. Write a program to print the following values as shown below:[B] Match the following pairs:¶
| Option A | Option B |
|---|---|
| a. Default value of sep in print( ) | 1. ' ' |
| b. Default value of end in print( ) | 2. Using fstring |
| c. Easiest way to print output | 3. Right justify num in 5 columns |
| d. Return type of split( ) | 4. Left justify num in 5 columns |
| e. print('{num:>5}') | 5. list |
| f. print('{num:<5}') | 6. \n |