Introduction

Published

2023-07-31

So far, we’ve provided all the values for our functions in our code. Things get a lot more interesting when the user can provide such values.

In this chapter, we’ll learn how to get input from the user and use it in our calculations. We’ll also learn how to format the output displayed to the user.

We call getting and displaying data this way as console I/O (“I/O” is just short for input/output).

We’ll also learn how to use Python’s f-strings (short for formatted string literals) to format output. For example, we can use f-strings with format specifiers to display floating point numbers to a specific number of digits to the right of the decimal place. With f-strings we can align strings for displaying data in tabular format.

Warning

In this text, we will use f-strings exclusively for formatting output. Beware! There’s a lot of stale information out there on the internet showing how to format strings in Python. For example, you may see the so-called printf-style (inherited from the C programming language), or the str.format() method. These alternate methods have their occasional uses, but for general purpose string formatting, your default should be to use f-strings.

Learning objectives

  • You will learn how to prompt the user for input, and handle input from the user, converting it to an appropriate type if necessary.
  • You will learn how to format strings using f-strings and interpolation.
  • You will learn how to use format specifiers within f-strings.
  • You will write programs which receive user input, and produce output based on that input, often performing calculations.

Terms and built-in functions introduced

  • command line interface (CLI)
  • console
  • constructor (int(), float(), and str())
  • f-string
  • format specifier
  • graphical user interface (GUI)
  • I/O (input/output)
  • input()
  • string interpolation

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).