Basic Input, Output, and String Formatting in Python

Basic Input, Output, and String Formatting in Python

by John Sturtz basics python

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:

  • Compared different paradigms used by programming languages to implement definite iteration
  • Learned about iterables and iterators, two concepts that form the basis of definite iteration in Python
  • Tied it all together to learn about Python’s for loops

By the end of this tutorial, you’ll know how to:

  • Take user input from the keyboard with the built-in function input()
  • Display output to the console with the built-in function print()
  • Format string data using Python f-strings

Without further ado, let’s dive in!

Reading Input From the Keyboard

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
>>> user_input = input()
foo bar baz
>>> user_input
'foo bar baz'

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
>>> name = input("What is your name? ")
What is your name? Winston Smith
>>> name
'Winston Smith'

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
 1>>> number = input("Enter a number: ")
 2Enter a number: 50
 3>>> print(number + 100)
 4Traceback (most recent call last):
 5  File "<stdin>", line 1, in <module>
 6TypeError: must be str, not int
 7
 8>>> number = int(input("Enter a number: "))
 9Enter a number: 50
10>>> print(number + 100)
11150

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.

Writing Output to 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
>>> first_name = "Winston"
>>> last_name = "Smith"

>>> print("Name:", first_name, last_name)
Name: Winston Smith

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
>>> example_list = [1, 2, 3]
>>> type(example_list)
<class 'list'>

>>> example_int = -12
>>> type(example_int)
<class 'int'>

>>> example_dict = {"foo": 1, "bar": 2}
>>> type(example_dict)
<class 'dict'>

>>> type(len)
<class 'builtin_function_or_method'>

>>> print(example_list, example_int, example_dict, len)
[1, 2, 3] -12 {'foo': 1, 'bar': 2} <built-in function len>

As you can see, even complex types like lists, dictionaries, and functions can be displayed to the console with print().

Printing With Advanced Features

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 arguments have the form <keyword>=<value>.
  • Any keyword arguments passed to 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().

Separating Printed Values

Adding the keyword argument sep=<str> causes Python to separate objects by <str> instead of by the default single space:

Python
>>> print("foo", 42, "bar")
foo 42 bar

>>> print("foo", 42, "bar", sep="/")
foo/42/bar

>>> print("foo", 42, "bar", sep="...")
foo...42...bar

>>> d = {"foo": 1, "bar": 2, "baz": 3}
>>> for k, v in d.items():
...     print(k, v, sep=" -> ")
...
foo -> 1
bar -> 2
baz -> 3

To squish objects together without any space between them, specify an empty string ("") as the separator:

Python
>>> print("foo", 42, "bar", sep="")
foo42bar

You can use the sep keyword to specify any arbitrary string as the separator.

Controlling the Newline Character

The keyword argument end=<str> causes output to be terminated by <str> instead of by the default newline:

Python
>>> if True:
...     print("foo", end="/")
...     print(42, end="/")
...     print("bar")
...
foo/42/bar

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
>>> for number in range(10):
...     print(number)
...
0
1
2
3
4
5
6
7
8
9

>>> for number in range(10):
...     print(number, end=(" " if number < 9 else "\n"))
...
0 1 2 3 4 5 6 7 8 9

You can use the end keyword to specify any string as the output terminator.

Sending Output to a Stream

print() accepts two additional keyword arguments, both of which affect how the function handles the output stream:

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

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

Using Formatted Strings

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
>>> name = input("What is your name? ")
What is your name? Winston

>>> age = int(input("How old are you? "))
How old are you? 24

>>> print(name)
Winston

>>> print(age)
24

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"Hello, {name}. You are {age}."
Hello, Winston. You are 24.

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
>>> f"Hello, {name}. In 50 years, you'll be {age + 50}."
Hello, Winston. In 50 years, you'll be 74.

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.

Python Input and Output: Conclusion

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:

  • Take user input from the keyboard with the built-in function input()
  • Display output to the console with the built-in function print()
  • Format string data using Python f-strings

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

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About John Sturtz

John is an avid Pythonista and a member of the Real Python tutorial team.

» More about John

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!