Printing To Console In Python

Console Input/Output in Python:

Console Input/Output output is most important as it acts as the basic text based interface
for the python programs. Almost all of us who learn programming start with writing a 
program that prints to the screen - "Hello World".

Console output in Python:

The built-in function print() of Python, prints any string passed to it to the screen.


print('Hello python world')

The above example prints the string 'Hello python world' to the console.

How to print integers and floating point numbers using print method?
The following sections present multiple ways to print basic python types to the console,
using the print method.

Python String formatting and printing:

Method1: Format using repr() and string concatenation operator:

a) Convert any type to string
b) Append the newly formed string with the use of string concatenation operator


Temperature = 80.5
print('Temperature today is '+repr(Temperature)+' Fahrenheit')

The repr() function provides the string format of any type. The String Concatenation +
appends this string to the main string to be printed.

In the above example, converting the floating point to string representation and 
concatenating is all done by the programmer.

Method2: Use the format method on string object:

Another way is to use the format method and the format fields available in python.
The other values like integer and floating point numbers can be placed in
the string by using the format field {}. The format method has to be called on that
string by passing the value to printed.

Temperature = 79.5
print('Temperature today is {} Fahrenheit'.format(Temperature))


Method3: C style printf like formating:

For die-hard c fans, the old style or c style formatting is still supported.
Where different format specifiers can be used with %<formatstring>.

Temperature = 78.5
print('Temperature today is %f Fahrenheit',%(Temperature))

Copyright 2023 ©