Python Output Statements

Python Output Using print() function

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

Example:

print(‘This sentence is displayed on the screen’)

 # Output: This sentence is displayed on the screen

Example:

In print() string can be written with in single quotes (‘ hello  ‘)

a = 5

print(‘value of a = ‘, a)

# Output:  value of a = 5

 Example:

In print() string can be written with in single quotes (” hello  “)

a=10

print(“Value of a = “,a)

# Output:  Value of a = 5

The actual syntax of the print() function is

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout)

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

Examples:

print(1,2,3,4)

# Output: 1 2 3 4

print(1,2,3,4,sep=‘*’)

# Output: 1*2*3*4

print(1,2,3,4,sep=‘#’,end=‘&’)

# Output: 1#2#3#4&

 

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

# Output: I love bread and butter

 print(‘I love {1} and {0}’.format(‘bread’,’butter’))

# Output: I love butter and bread

 We can even use keyword arguments to format the string.

>>> print(‘Hello {name}, {greeting}’.format(greeting = ‘Goodmorning’, name = ‘Amit’))

Hello Amit, 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)

The value of x is 12.35

>>> print(‘The value of x is %3.4f’ %x)

The value of x is 12.3457

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling