https://www.codebread.co.in/input-output-in-python-using-input-and-print-function
https://www.python-course.eu/python3_formatted_output.php
You use the print() function to display output in a Python program.
print('Hello world')
The quote marks simply specify the beginning and the end of the text that you wish to display.
Note: Starting with Python 3.x, print() is a function rather than a statement. You can easily find out how crucial this difference is, if you take an arbitrary Python program written in version 2.x and if you try to let it run with a Python3 interpreter. In most cases you will receive error messages. One of the most frequently occurring errors will be related to print, because most programs contain prints. We can generate the most typical error in the interactive Python shell:
>>> print 42 File "", line 1 print 42 ^ SyntaxError: invalid syntax >>>
This is a familiar error message for most of us: We have forgotten the parentheses. “print” is – as we have already mentioned – a function in version 3.x. Like any other function print expects its arguments to be surrounded by parentheses. So parenthesis are an easy remedy for this error:
>>> print(42) 42 >>>
But this is not the only difference to the old print. The output behaviour has changed as well.
Print by default provides an interface to the standard output(sys.stdout) object. When you use print, you are asking your Python interpreter to echo your message to standard output. For example, you can also print a message, without using print.
# Python 2 and Python 3
import sys
sys.stdout.write('Hello World')
>>> Hello World
You use the write() method in sys.stdout to output your message to the standard output stream. Print is just easier to use and comprehend.
General syntax of print() function in Python 3 :
# Python 3 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The arguments of the print function are the following ones:
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
The print function can print an arbitrary number of values (“value1, value2, …”), which are separated by commas. Python converts the objects into strings(if they are not strings) and then writes to the standard output stream. These values when displayed on standard output stream are separated by blanks.
In the following example we can see two print calls. We are printing two values in both cases, i.e. a string and a float number:
The easiest way, but not the most elegant one:
- We used print with a comma separated list of values to print out the results, as we can see in the following example.
- All the values are separated by blanks, which is the default behaviour.
# Python 3
print('Python', 3, 'Rocks')
>>> Python 3 Rocks
>>> q = 459 >>> p = 0.098 >>> print(q, p, p * q) 459 0.098 44.982
By default, the output items are separator by space.
>>> print("Good", "Morning", 'John')
Good Morning John
We can change the default value to an arbitrary string, if we assign this string to the keyword parameter “sep” of the print function:
>>> print(q, p, p * q, sep = ",")
459,0.098,44.982
>>> print(q, p, p * q, sep = "|")
459|0.098|44.982
>>> print("Good", "Morning", 'John', sep = ",")
Good,Morning,John
By default, print goes to a new line after printing the inputted text.
print("Python")
print("is")
print("easy")
Python
is
easy
We can use ‘end‘ keyword if we want two print() function outputs printed on the same line separated by space between them.
print("Python", end = " ")
print("is", end = " ")
print("easy")
Python is easy
We can also define special characters for end keyword like example below.
>>> print('python', 20, 45.0, sep = ",", end = "!!\n")
Python, 20, 45.0!!
Note: The default value for end attribute is ‘\n’, which is nothing but a new line character.
Using string module (%) operator
With string operands, the modulo operator has an entirely different function: string formatting.
The syntax of the string modulo operator looks like:
<format_string> % <values>
On the left side of the % operator, <format_string> is a string containing one or more conversion specifiers. The <values> on the right side get inserted into <format_string> in place of the conversion specifiers. The resulting formatted string is the value of the expression.
print("<format_string>" % (set of variables) )
The argument specifiers in formatted string for different Python data types are as below:
The %s operator can be used for object which is not a string. Like in the below code, we can format list items by using %s operator.
print() using string format() method
The format() method is added in Python 2.6. The general form of this method looks like below:
syntax:
(formatted_string).format(argument_list)
We can use the above form directly in print() function.
The formatted string is a string which contains one or more format codes (fields to be replaced) along with the constant text. The fields to be replaced are surrounded by curly braces {}. The curly braces and the code inside will be substituted with a formatted value from arguments. Any text which is not in curly braces will be exactly printed without any changes.
The list of arguments starts with zero or more positional arguments or zero or more keyword arguments of the form name = value (key-value) pair. A positional parameter of the format method can be accessed by defining the index of the parameter inside the curly braces, e.g. {0} will access the first parameter of the argument list, {1} will access the second parameter and so on.
>>> name = "Pradnya"
>>> salary = 40000
>>> age = 23
>>> print("Hello {0} Your salary is {1} and age is {2}".format(name, salary, age))
Hello Pradnya Your salary is 40000 and age is 23
>>> print("Hello {x} Your salary is {y} and age is {z}".format(x = name, y = salary, z = age))
Hello Pradnya Your salary is 40000 and age is 23
Flushing
Usually Python buffers the messages that you want to print until it gets a newline(\n). Using the flush argument in Python 3, you can directly print the message to the standard output stream without having to wait for the sleep time to finish.
from time import sleep
print('Will it get printed immediately?', end='', flush=True)
sleep(5)
Python code examples:
# print function syntax :
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
# objects - object to the printed. * indicates that there may be more than one object
# sep - objects are separated by sep. Default value - space : ' '
# end - end is printed at last. Default value - '\n'
# file - must be an object with write(string) method. If omitted it, sys.stdout will be used
# flush - If True, the stream is forcibly flushed. Default value: False
# Note: sep, end, file and flush are keyword arguments.
print("Hello, World!")
# printing multiple elements
print('Python', 3, 'Rocks') # output : Python 3 Rocks
# using different separator
print('Python', 3, 'Rocks', sep ='|') # output : Python|3|Rocks
# using end keyword argument
# without using 'end' keyword arguments, these two statements will be
# printed on different lines
print('Python', 3, 'Rocks!', end =' ')
print('I love Python!!') # output : Python 3 Rocks! I love Python!!
# using format
print("{}, Welcome to {}!".format("Raghu", "Python"))
# output : Raghu, Welcome to Python!!
# using positional index with format
print("{0}, Welcome to {1}!!".format("Raghu", "Python"))
# using reverse positional indexing
print("{1}, Welcome to {0}!!".format("Python", "Raghu"))
# using keyword positional indexing
print("{user}, Welcome to {lang}!!!".format(lang="Python", user="Raghu"))
# output : Raghu, Welcome to Python!!!
# without print() function
import sys
sys.stdout.write("Hello, World!!") # output : Hello, World!!