0% found this document useful (0 votes)
19 views9 pages

Chap - 4

The document discusses input and output in Python programs. It covers the print() function for output, the input() function for user input, formatting output using methods like str.format(), and splitting strings using the split() method. Escape characters are also described for formatting string output.

Uploaded by

Parth Khurana
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)
19 views9 pages

Chap - 4

The document discusses input and output in Python programs. It covers the print() function for output, the input() function for user input, formatting output using methods like str.format(), and splitting strings using the split() method. Escape characters are also described for formatting string output.

Uploaded by

Parth Khurana
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/ 9

Data Input and Output 4-1

Chapter
4

Data Input and Output


Key Topics
4.1. Introduction
4.1. Introduction
4.2. Python Input, Output And Import
There are three essential features of a program, the data
4.2.1. Python Output Using Print() input, processing the data and output/display/print the data in
Function certain format. There are many ways to provide Input to a
4.2.1.1. Output Formatting
4.2.1.2. Escape Characters
program and similarly many ways to get Output from a program.
4.2.1.3. Split ( ) Method
4.2.2. Python Input
4.2.2.1. input() Parameters The data is inputted to the program by either assigning some
4.2.2.2. Return value from values to the variable e.g. a=5;b=6; or entered through input( )
input()
4.2.3. Python Import function. For output/print/display we use print( ) function
Most common input device is Keyboard from where user
can enter data, and most common output device is Screen (VDU)
where produced output can be shown to user. All C input/output
is done with streams, no matter where input is coming from or
where output is going to.

4.2. Python Input, Output And Import


There are two built-in functions print( ) and input( ) to
perform I/O task in Python. Also, you will learn to import modules
and use them in your program.
Python provides numerous built-in functions that are readily
available to us at the Python prompt. Let us see the output section
first.

4.2.1. Python Output Using print( ) Function


We use the print( ) function to output data to the standard output
device (screen). We can also output data to a file, but this will be
discussed later. An example use is given below.
4-2 Data Input and Output
print('This sentence is output to the screen')
a=5
print('The value of a is', a)
Output
This sentence is output to the screen
The value of a is 5
In the second print() statement, we can notice that a space was added between the string and
the value of variable a.This is by default, but we can change it.
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout (screen).
Here are an example to illustrate this.
print(1,2,3,4)
print(1,2,3,4,sep='*')
print(1,2,3,4,sep='#',end='&')
Output
1234
1*2*3*4
1#2#3#4&

4.2.1.1. Output Formatting


Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in which it is
printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Data Input and Output 4-3
Output
Hello John, Goodmorning
We can even format strings like the old sprintf() style used in C programming language. We
use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
>>> print('The value of x is %3.4f' %x)
Output
The value of x is 12.35
The value of x is 12.3457

4.2.1.2. Escape Characters


Another way to format strings is to use an escape character. Escape characters all start with
the backslash key ( \ ) combined with another character within a string to format the given string a
certain way.
Here is a list of several of the common escape characters:
Escape character How it formats
\ New line in a multi-line string
\\ Backslash
\' Apostrophe or single quote
\" Double quote
\n Line break
\t Tab (horizontal indentation)
Let's use an escape character to add the quotation marks to the example on quotation marks
above, but this time we'll use double quotes:
print("Rajesh says, \"Hello!\"")
Output
Rajesh says, "Hello!"
By using the escape character \" we are able to use double quotes to enclose a string that
includes text quoted between double quotes.
Similarly, we can use the escape character \' to add an apostrophe in a string that is enclosed in
single quotes:
print('Rajesh\'s balloon is red.')
Output
Rajesh's balloon is red.
4-4 Data Input and Output
Because we are now using the escape character we can have an apostrophe within a string
that uses single quotes. Similarly, we can use the \n escape character to break lines without hitting
the enter or return key:
print("This string\nspans multiple\nlines.")
Output
This string
spans multiple
lines.
We can combine escape characters, too. Let's print a multi-line string and include tab spacing
for an itemized list, for example:
print("1.\tShark\n2.\tShrimp\n10.\tSquid")
Output
1. Shark
2. Shrimp
10. Squid
The horizontal indentation provided with the \t escape character ensures alignment within the
second column in the example above, making the output extremely readable for humans.
Though the \n escape character works well for short string literals, it is important to ensure that
source code is also readable to humans. In the case of lengthy strings, the triple quote approach to
multi-line strings is often preferable.
Escape characters are used to add additional formatting to strings that may be difficult or
impossible to achieve. Without escape characters, how would you construct the string Rajesh says,
"The balloon's color is red."?

4.2.1.3. Split ( ) Method


The split() method breaks up a string at the specified separator and returns a list of strings.
The split() breaks the string at the separator and returns a list of strings.
text= 'Love thy neighbor'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# splits at ','
print(grocery.split(', '))
# Splitting at ':'
print(grocery.split(':'))
Output
['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
Data Input and Output 4-5
#Get list (int,str) input from user with a prompt
a = [int(x) for x in input().split()]
list = [list(x) for x in input().split()]
print(a)
print(list)
Output
[1, 3, 4]
[['h', 'e', 'l', 'l', 'o'], ['h', 'o', 'w'], ['a', 'r', 'e'], ['u']]

4.2.2. Python Input


Up till now, our programs were static. The value of variables were defined or hard coded into
the source code.
Input can come in various ways, for example from a database, another computer, mouse clicks
and movements or from the internet. Yet, in most cases the input stems from the keyboard. For this
purpose, Python provides the function input(). input has an optional parameter, which is the prompt
string.
If the input function is called, the program flow will be stopped until the user has given an input
and has ended the input with the return key. The text of the optional parameter, i.e. the prompt, will
be printed on the screen.
The input of the user will be interpreted. If the user e.g. puts in an integer value, the input
function returns this integer value. If the user on the other hand inputs a list, the function will return
a list.
To allow flexibility we might want to take the input from the user. In Python, we have the input
( ) function to allow this.
The syntax for input( ) is
input([prompt])

4.2.2.1. input( ) Parameters


The input() method takes a single optional argument:
• prompt (Optional) - a string that is written to standard output (usually screen) without trailing
newline

4.2.2.2. Return value from input( )


The input() method reads a line from input (usually user), converts the line into a string by
removing the trailing newline, and returns it.
If EOF is read, it raises an EOFError exception.
#Get string input from user with a prompt
# get input from user
inputString = str(input('Enter a string:'))
print('The inputted string is:', inputString)
4-6 Data Input and Output
Output
Enter a string: Python is interesting.
The inputted string is: Python is interesting
#Get integer input from user with a prompt
# get input from user
inputint = int(input('Enter a Integer:'))
print('The inputted Integer is:', inputint)
Output
Enter a Integer: 34.
The inputted Integer is: 34
#Get integer,string input from user with a prompt
name = str(input("What's your name? "))
age = int(input("Your age? "))
print(name, type(name))
print(age, type(age))
colours = str(input("Your favourite colours? "))
print(colours)
print(colours, type(colours))
Output
What's your name? Rajesh
Your age? 34
Rajesh <class 'str'>
34 <class 'int'>
Your favourite colours? ["red","green"]
["red","green"]
["red","green"] <class 'str'>

4.2.3. Python Import


When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
Python Fractions : Python provides operations involving fractional numbers through its fractions
module.
A fraction has a numerator and a denominator, both of which are integers. This module has
support for rational number arithmetic.
Data Input and Output 4-7
We can create Fraction objects in various ways.
import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))
# Output: 3/2
# Output: 5
# Output: 1/3
Python Mathematics : Python offers modules like math and random to carry out different
mathematics like trigonometry, logarithms, probability and statistics, etc.
import math
print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))
Output
# Output: 3.141592653589793
# Output: -1.0
# Output: 22026.465794806718
# Output: 3.0
# Output: 1.1752011936438014
# Output: 720
import random
print(random.randrange(10,20))
x = ['a', 'b', 'c', 'd', 'e']
print(random.choice(x))
random.shuffle(x)
print(x)
print(random.random())
# Output: 16
# Get random choice
# Shuffle x
# Print the shuffled x
# Print random element
4-8 Data Input and Output
1. Will the following lines of code print the same thing? Explain why or why not.
x=6
print(6)
print("6")
2. Will the following lines of code print the same thing? Explain why or why not.
x=7
print(x)
print("x")

You might also like