Python input output write

Basic Input, Output, and String Formatting in Python

Basic Input, Output, and String Formatting in 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!

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

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() :

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:

>>> 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 argument, then input() displays it as a prompt so that your user knows what to input:

>>> 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:

 1>>> number = input("Enter a number: ") 2Enter a number: 50  3>>> print(number + 100)  4Traceback (most recent call last): 5 File "", line 1, in  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.

Python Version Note: Should you find yourself working with Python 2.x code, you might bump into a slight difference in the input functions between Python versions 2 and 3.

raw_input() in Python 2 reads input from the keyboard and returns it. raw_input() in Python 2 behaves just like input() in Python 3, as described above.

But Python 2 also has a function called input() . In Python 2, input() reads input from the keyboard, parses and evaluates it as a Python expression, and returns the resulting value.

Python 3 doesn’t provide a single function that does exactly what Python 2’s input() does. You can mimic the effect in Python 3 with the expression eval(input()) . However, this is a security risk because it allows users to run arbitrary, potentially malicious code.

For more information on eval() and its potential security risks, check out Python eval(): Evaluate Expressions Dynamically.

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(, . )

Displays a string representation of each to the console. (Documentation)

By default, print() separates objects by a single space and appends a newline to the end of the output:

>>> 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:

>>> example_list = [1, 2, 3] >>> type(example_list) >>> example_int = -12 >>> type(example_int) >>> example_dict = "foo": 1, "bar": 2> >>> type(example_dict) >>> type(len) >>> print(example_list, example_int, example_dict, len) [1, 2, 3] -12

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 = .
  • 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= causes Python to separate objects by instead of by the default single space:

>>> 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:

>>> 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= causes output to be terminated by instead of by the default newline:

>>> 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:

>>> 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= : By default, print() sends its output to a default stream called sys.stdout , which is usually equivalent to the console. The file= argument causes print() to send the output to an alternate stream designated by 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.

Note: The f-string syntax is one of the modern ways of string formatting. For an in-depth discussion, you may want to check out these tutorials:

You’ll also get a more detailed overview of two approaches for string formatting, f-strings and str.format() , in the tutorial on formatted string output in Python, which follows this tutorial in this introductory series.

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:

>>> 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:

>>> 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:

>>> 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!

Note: If you want to learn more about using this convenient string formatting technique, then you can dive deeper into the guide on Python 3’s f-Strings.

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.

Источник

Читайте также:  Image borders html and css
Оцените статью