Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Reading Input and Writing Output in Python
For a program to be useful, it usually needs to communicate with the outside world by obtaining input data from the user and displaying result data back to the user. In this tutorial, you’ll learn about Python input and output.
Input may come from the user directly through the keyboard or from external sources like files or databases. Output can be displayed directly to the console or IDE, to the screen through a Graphical User Interface (GUI), or again to an external source.
In the previous tutorial in this introductory series, you:
By the end of this tutorial, you’ll know how to:
input()print()Without further ado, let’s dive in!
Programs often need to obtain data from the user, usually by way of input from the keyboard. One way to accomplish this in Python is with input():
input([<prompt>])Reads a line from the keyboard. (Documentation)
The input() function pauses program execution to allow the user to type in a line of input from the keyboard. Once the user presses the Enter key, all characters typed are read and returned as a string:
Python
Note that your return string doesn’t include the newline generated when the user presses the Enter key.
If you include the optional <prompt> argument, then input() displays it as a prompt so that your user knows what to input:
Python
input() always returns a string. If you want a numeric type, then you need to convert the string to the appropriate type with the built-in int(), float(), or complex() function:
Python
In the example above, the expression number + 100 on line 3 is invalid because number is a string and 100 is an integer. To avoid running into this error, line 8 converts number to an integer right after collecting the user input. That way, the calculation number + 100 on line 10 has two integers to add. Because of that, the call to print() succeeds.
With input(), you can collect data from your users. But what if you want to show them any results that your program calculated? Up next, you’ll learn how you can display output to your users in the console.
In addition to obtaining data from the user, a program will also usually need to present data back to the user. You can display program data to the console in Python with print().
To display objects to the console, pass them as a comma-separated list of arguments to print().
print(<obj>, ..., <obj>)Displays a string representation of each
<obj>to the console. (Documentation)
By default, print() separates objects by a single space and appends a newline to the end of the output:
Python
You can specify any type of object as an argument to print(). If an object isn’t a string, then print() converts it to an appropriate string representation before displaying it:
Python
As you can see, even complex types like lists, dictionaries, and functions can be displayed to the console with print().
print() takes a few additional arguments that provide modest control over the format of the output. Each of these is a special type of argument called a keyword argument. Later in this introductory series, you’ll encounter a tutorial on functions and parameter passing so that you can learn more about keyword arguments.
For now, though, here’s what you need to know:
<keyword>=<value>.print() must come at the end, after the list of objects to display.In the following sections, you’ll see how these keyword arguments affect console output produced by print().
Adding the keyword argument sep=<str> causes Python to separate objects by <str> instead of by the default single space:
Python
To squish objects together without any space between them, specify an empty string ("") as the separator:
Python
You can use the sep keyword to specify any arbitrary string as the separator.
The keyword argument end=<str> causes output to be terminated by <str> instead of by the default newline:
Python
For example, if you’re displaying values in a loop, you might use end to cause the values to be displayed on one line, rather than on individual lines:
Python
You can use the end keyword to specify any string as the output terminator.
print() accepts two additional keyword arguments, both of which affect how the function handles the output stream:
file=<stream>: By default, print() sends its output to a default stream called sys.stdout, which is usually equivalent to the console. The file=<stream> argument causes print() to send the output to an alternate stream designated by <stream> instead.
flush=True: Ordinarily, print() buffers its output and only writes to the output stream intermittently. flush=True specifies that Python forcibly flushes the output stream with each call to print().
These two keyword arguments are presented here for the sake of completeness. You probably don’t need to be too concerned about output streams at this point of your learning journey.
While you can go deep learning about the Python print() function, the formatting of console output that it provides is rudimentary at best. You can choose how to separate printed objects and specify what goes at the end of the printed line. That’s about it.
In many cases, you’ll need more precise control over the appearance of data destined for display. Python provides several ways to format output string data. In this section, you’ll see an example of using Python f-strings to format strings.
In this section, you’ll use f-strings to format your output. Assume you wrote some code that asks your user for their name and their age:
Python
You’ve successfully collected the data from your user, and you can also display it back to their console. To create a nicely formatted output message, you can use the f-string syntax:
Python
f-strings allow you to put variable names into curly braces ({}) to inject their value into the string you’re building. All you need to do is add the letter f or F at the beginning of your string.
Next, assume that you want to tell your user how old they’ll be 50 years from now. Python f-strings allow you to do that without much overhead! You can add any Python expression in between the curly braces, and Python will calculate its value first, then inject it into your f-string:
Python
You’ve added 50 to the value of age that you collected from the user and converted to an integer using int() earlier on. The whole calculation took place inside the second pair of curly braces in your f-string. Pretty cool!
Python f-strings are arguably the most convenient way to format strings in Python. If you only want to learn one way, it’s best to stick with Python’s f-strings. However, this syntax has only been available since Python 3.6, so if you need to work with older versions of Python, then you’ll have to use a different syntax, such as the str.format() method or the string modulo operator.
In this tutorial, you learned about input and output in Python and how your Python program can communicate with the user. You’ve also explored some of the arguments you can work with to add a message to the input prompt or customize how Python displays the output back to your users.
You’ve learned how to:
input()print()In the following tutorial of this introductory series, you’ll learn about another string formatting technique, and you’ll dive deeper into using f-strings.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Reading Input and Writing Output in Python