Python Output
We'll cover the following...
The print() method in Python
The print() method is a built-in method offered by Python that allows a user to display output to the console.
Let’s output a simple string that says “Hello from Educative!” to the console.
We can also output variables of any datatype to the console simply using the print() method. Let’s print a few data types, including integers, floats, booleans, strings, lists, dictionaries, and tuples.
Parameters
The print() method consists of various parameters that we can customize according to our needs.
print(object= , separator=, end=, file=, flush=)
Parameters | Explanation |
object | Value to print |
sep | Specify the separating character between printed strings (defaults to “ “) |
end | Append characters to the end of the printed value (defaults to newline char (“\n”)). |
file | Location of printed values (defaults to the screen) |
flush | If output is to be flushed (defaults to False) |
Run the code below to see this in action!
Formatted strings
Formatted strings, or f-strings, are a recent addition by Python, and they provide a highly concise way to embed expressions inside string literals. This makes the output formatting quite straightforward for use and more readable for readers as well.
We can also format more than one variable with varying data types. This is achieved using the format() method.
The format() method is applied to a string and receives the variables to format as parameters. Let’s output a user’s name and age together.
Formatting numeric output
Python allows its users to specify the number of decimal places to output, as well as other formatting options combined with the print statement.
Error handling in the output
It’s crucial to handle potential errors in the code, or else the program can crash or cause unexpected behavior. The ‘try’ and ‘except’ blocks can be used to catch such errors, and ‘print’ can be used alongside them to output the error.