I/O in Python


Python provides number of built-in functions that can be used to perform different type of operations.

Built-in function print() and input() are widely used for standard input and output operations respectively


Python Output Using print( ) function :


We use the print() function to show output data to the standard output device (screen).

#script.py

print("This will print on screen")
v = 5
k = 10
print(v)
print(v,k)
print("The value of v =",v,"and k=",k)
OUTPUT :
This will print on screen
5
5 10
The value of v = 5 and k= 10

Let's understand the print( ) statement :

  • In, first print() statement we are printing only string.

  • In, second print() statement we are printing only one variable value.

  • In, third print() statement as we can see, we are printing two variable's values, and each one is separated by comma ( , )

    and
  • In, last print() statement we are printing mix values.

Comma ( , ) by default add one space as we can see in the example, but we can change it as per our requirement.


Syntax of print( ) :

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. By defaults it is space character.

  • After all values are printed, end is printed. Its default is new line.

  • The file is the object where the values are printed and its default value is sys.stdout (screen).

example to illustrate

#script.py
print(1,2,3,4)  default separator
# Output: 1 2 3 4

print(1,2,3,4,sep='*') separator change to *
# Output: 1*2*3*4

print(1,2,3,4,sep='#',end='&') separator and end change
# Output: 1#2#3#4&
OUTPUT
1 2 3 4
1*2*3*4
1#2#3#4&

Output Formatting :


Often we want more control over the formatting of our output than simply printing space-separated values.

There are two ways to format our output :

The first way is to do all the string handling like slicing, concatenation etc... The string type has some methods that perform useful operations for padding strings to a given column width.

The second way is to use formatted string literals, or the str.format( ) method.


1. Formatting using string functions :

Python has ways to convert any value to a string: pass it to the repr( ) or str( ) functions.

The str( ) function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter

Example :

>>> s = 'Hello, world.'
>>> str(s) 
'Hello, world.'
>>> repr(s) 
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
>>> hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
>>> repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

str.rjust(), str.ljust() and str.center() methods :

# str.rjust() method right-justifies a string
  #in a field of a given width by padding 
  #it with spaces on the left.

>>> print(repr(100).rjust(5))
  100  as we can see output is after padding

# To better understand let's write a table of squares and cubes

>>> for x in range(1, 11):
	print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
	# Note use of 'end' on previous line
	print(repr(x*x*x).rjust(4))
	
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

 As we can see all values are right-justified

# similarly str.ljust() and str.center() works.
                

2. Formatting using str.format() :


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

Curly braces {} are used as placeholders. When we pass values into format() method, they automatically replaced in the order we pass.


A number in the brackets can be used to refer to the position of the object passed into the str.format()method.


>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
           

We can even use keyword arguments to format the string.

If keyword arguments are used in the str.format() method, their values are referred to by using the name of the argument.


>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'Daneyal'))
Hello Daneyal, Goodmorning                
                

Positional and keyword arguments can be arbitrarily combined:


>>>  print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
The story of Bill, Manfred, and Georg.
                

printf-style String Formatting :

The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.


>>> x, y = 25, 3.14
>>> print('x = %d and y = %f'%(x,y))
x = 25 and y = 3.140000
>>> x = 10.1234567
>>> print('The value of x is %3.2f' %x)
The value of x is 10.12
>>> print('The value of x is %3.4f' %x)
The value of x is 10.1235                    
                


Python Input

To take user input in python we use builtin function input().

Syntax :

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

IN python 3.x, whatever the value you will take input from user, that will be string.
Means input() function return string always, and if we want to take another type of value then we will do typecasting.

Example :


>>> name = input('Enter a name: ')
Enter a name: prowessapps
>>> name
'prowessapps'  string
>>> num = input('Enter a number: ')
Enter a number: 12
>>> num
'12'   It is also string
                

Here, we can see that the entered value 12 is a also string, not a number. To convert this into a number we can use int() or float() functions.


>>> int(num)
12
>>> float(num)
12.0
>>>                    
    

Next chapter is if.. in python





 




Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved