Python Input and Output Statements
Input : Any information or data sent to the computer from the user through the keyboard is called input.
Output: The information produced by the computer to the user is called output.
Python provides us with the two inbuilt functions as input() and output().
The syntax for input is input(prompt_message); the python will automatically identify whether the user entered a string, number, or list; if the input entered from the user is not correct, then python will throw a syntax error.
And the syntax for the output in python is print(), normally used to print the output.
- Python-2 supports the raw_input() function and input() function
- Python-3 supports only for input() function .
The following example will read two inputs from the keyboard and print the sum

Let us consider another example to know how we can use the input() function. The Following example read the employee data from the keyboard and print that data.

In the below example, I am going to give, Married status as False but still, python is printing the output as True only; this happens because we are converting the string into Boolean Datatype.

Python gives False while converting the string into a boolean, only in the non-string or empty string case.
But here whether the value is True or False python will consider the value as string data type and print True only; so to overcome this problem we have to use the Eval Function instead of Bool Function.
eval() Function
The return type of eval() function is automatically considered based on what argument is passed to the eval() function.
If the argument represents a string, then the eval() function also returns a string. If you pass an argument as int, float, string, boolean, it will return the corresponding datatype only. The eval() function is used as an alternate for typecasting.Let us see some examples for eval().


eval() with float value

eval() with boolean value

eval() with string value

eval() with list

eval() with tuple value
And you can pass the expressions

So let us use the eval() function in the employee data program and execute the program


Now, let us understand how to read multiple values from the keyboard in a single line

In the above program, when the user enters two values/numbers, the python will consider those values as one single string, but what we are looking for is two numbers/values. To retrieve those two values, we need to split the string.
Split () function breaks a single string into multiple strings using a delimiter. By default, split() function considers space as delimiter.
And if you wanted to split the numbers with a comma, then you can pass the argument as split(«,»)

In our next example, we are going to read three inputs from the keyboard with comma separation and print the Sum.
In this example also I am going to include all the operations in a single line; let me explain to you line by line.
First, I am going to enter the three float values as an input, and here I am passing the split() to separate those three values with comma as split(«,»).
Next, for each x in input() function, convert into float datatype, so I am passing
And next, I am going to assign these values into three variables
Now, print the sum of these three variables

And Hence the output is
Python Output statements
The python output() is used to print the output for the end-user by taking the input from the keyboard. The only possibility to print the output is by using the print() statement.

-
Printing the print statement without any arguments. Let us see how it will work
So if we try to print the print() statement without any arguments, then it will add an empty line between the two outputs.
While printing the string arguments, we can use the escape characters like newline command( \n), tab command (\t) in between arguments.
- In the same way, we can also use the + operator to perform concatenation and the * operator to repeat the string. But the important thing is that, while using the + operator, both the arguments must be string only, and while using the star(*) operator, one argument must be of int type, and another must be of a string data type.

Next, a print statement with any number of arguments is acceptable, in the following example I am going to pass four arguments with comma separation, accepting a variable number of arguments is one of the beautiful features of the print() statement.

The print statement with sep Attribute
The Separator between the arguments in print () statement by default is the space in python, by using the sep parameter, we can change space into any character, integer, or string type.
The sep attribute supports only in python 3.x versions; we can also format the output by using the sep attribute.
The syntax for the sep attribute is as follow:

In the above example, I have mentioned the sep attribute as colon(:), you can choose which separator you want based on your requirement.

For disabling the soft space between the arguments, we can use an empty string like this «.»

The print() statement with end Attribute
Every print() is going to print the output in a new line; by using the end attribute, we can make the output print in a single line.
The default value of the end attribute is a new line, let us see how we can make use of the end attribute in printing the output by using the print() statement.

Instead of soft space, we can also make use of a colon(:), an asterisk(*), and at the rate symbols, etc.
end attribute by using the @ symbol

End attribute by using colon(:)

end attribute by using the $ symbol

Using the sep attribute with end attribute

A print statement with Object
The print statement cannot take string only as its arguments; instead, we can use any arguments with the print() statement.
Below examples showcase you different types of arguments with print() statements
Print() statement with Replace() Function
The replace () is an inbuilt function of python, where replace() is going to returns the copy of a string with the substring where we had specified. The replacement operator is specified with the <> symbol.
The syntax for replace operator is:
- old: old substring which you want to replace
- new: new substring which is going to replace the old substring
- count(optional): The number of times you wish to return the old substring with a unique substring.
The following example demonstrates the use of replacing (), operator
example:1
Python Programming/Input and Output
Python 3.x has one function for input from user, input() . By contrast, legacy Python 2.x has two functions for input from user: input() and raw_input() .
There are also very simple ways of reading a file and, for stricter control over input, reading from stdin if necessary.
input() in Python 3.x [ edit | edit source ]
In Python 3.x, input() asks the user for a string of data (ended with a newline), and simply returns the string. It can also take an argument, which is displayed as a prompt before the user enters the data. E.g.
Example: to assign the user’s name, i.e. string data, to a variable «x» you would type
In legacy Python 2.x, the above applies to what was raw_input() function, and there was also input() function that behaved differently, automatically evaluating what the user entered; in Python 3, the same would be achieved via eval(input()) .
-
in Built-in Functions in Library Reference for Python 3, docs.python.org in Built-in Functions in Library Reference for Python 2, docs.python.org
input() in Python 2.x [ edit | edit source ]
In legacy Python 2.x, input() takes the input from the user as a string and evaluates it.
Therefore, if a script says:
it is possible for a user to input:
which yields the correct answer in list form. Note that no inputted statement can span more than one line.
input() should not be used for anything but the most trivial program, for security reasons. Turning the strings returned from raw_input() into Python types using an idiom such as:
is preferable, as input() uses eval() to turn a literal into a Python type, which allows a malicious person to run arbitrary code from inside your program trivially.
-
in Built-in Functions in Library Reference for Python 2, docs.python.org
File Input [ edit | edit source ]
File Objects [ edit | edit source ]
To read from a file, you can iterate over the lines of the file using open:
This will print the first character of each line. A newline is attached to the end of each line read this way. The second argument to open can be ‘r’, ‘w’, or ‘rw’, among some others.
The newer and better way to read from a file:
The advantage is that the opened file will close itself after finishing the part within the with statement, and will do so even if an exception is thrown.
Because files are automatically closed when the file object goes out of scope, there is no real need to close them explicitly. So, the loop in the previous code can also be written as:
You can read a specific numbers of characters at a time:
This will read the characters from f one at a time, and then print them if they’re not whitespace.
A file object implicitly contains a marker to represent the current position. If the file marker should be moved back to the beginning, one can either close the file object and reopen it or just move the marker back to the beginning with:
Standard File Objects [ edit | edit source ]
There are built-in file objects representing standard input, output, and error. These are in the sys module and are called stdin, stdout, and stderr. There are also immutable copies of these in __stdin__, __stdout__, and __stderr__. This is for IDLE and other tools in which the standard files have been changed.
You must import the sys module to use the special stdin, stdout, stderr I/O handles.
For finer control over input, use sys.stdin.read(). To implement the UNIX ‘cat’ program in Python, you could do something like this:
Note that sys.stdin.read() will read from standard input till EOF. (which is usually Ctrl+D.)
Parsing command line [ edit | edit source ]
Command-line arguments passed to a Python program are stored in sys.argv list. The first item in the list is name of the Python program, which may or may not contain the full path depending on the manner of invocation. sys.argv list is modifiable.
Printing all passed arguments except for the program name itself:
Parsing passed arguments for passed minus options:
Above, the arguments at which options are found are removed so that sys.argv can be looped for all remaining arguments.
Parsing of command-line arguments is further supported by library modules optparse (deprecated), argparse (since Python 2.7) and getopt (to make life easy for C programmers).
A minimum parsing example for argparse:
Parse with argparse—specify the arg type as int:
Parse with argparse—add optional switch -m to yield multiplication instead of addition:
Parse with argparse—set an argument to consume one or more items:
Usage example: python ArgparseTest.py 1 3 5
Parse with argparse—as above but with a help epilog to be output after parameter descriptions upon -h:
Parse with argparse—make second integer argument optional via nargs:
-
, docs.python.org , docs.python.org , docs.python.org , docs.python.org , docs.python.org
Output [ edit | edit source ]
The basic way to do output is the print statement.
To print multiple things on the same line separated by spaces, use commas between them:
This will print out the following:
While neither string contained a space, a space was added by the print statement because of the comma between the two objects. Arbitrary data types can be printed:
This will output the following:
Objects can be printed on the same line without needing to be on the same line:
This will output the following:
To end the printed line with a newline, add a print statement without any objects.
This will output the following:
If the bare print statement were not present, the above output would look like:
You can print to a file instead of to standard output:
This will print to any object that implements write(), which includes file objects.
Note on legacy Python 2: in Python 2, print is a statement rather than a function and there is no need to put brackets around its arguments. Instead of print(i, end=" "), one would write print i,.
Omitting newlines [ edit | edit source ]
In Python 3.x, you can output without a newline by passing end=»» to the print function or by using the method write:
In Python 2.x, to avoid adding spaces and newlines between objects’ output with subsequent print statements, you can do one of the following:
Concatenation: Concatenate the string representations of each object, then later print the whole thing at once.
This will output the following:
Write function: You can make a shorthand for sys.stdout.write and use that for output.
This will output the following:
You may need sys.stdout.flush() to get that text on the screen quickly.
Examples [ edit | edit source ]
Examples of output with Python 3.x:
- from __future__ import print_function
- Ensures Python 2.6 and later Python 2.x can use Python 3.x print function.
- Prints the two words separated with a space. Notice the surrounding brackets, ununsed in Python 2.x.
- Prints without the ending newline.
- Prints the two words separated with a dash.
- Prints elements of various data types, separating them by a space.
- Throws an error as a result of trying to concatenate a string and an integer.
- Uses «+» to concatenate strings, after converting a number to a string.
- Prints a string that has been formatted with the use of an integer passed as an argument. See also #Formatting.
- print («Error», file=sys.stderr)
- Outputs to a file handle, in this case standard error stream.
Examples of output with Python 2.x:
- print «Hello»
- print «Hello», «world»
- Separates the two words with a space.
- Prints elements of various data types, separating them by a space.
- Throws an error as a result of trying to concatenate a string and an integer.
- Uses «+» to concatenate strings, after converting a number to a string.
- Prints «Hello » without a newline, with a space at the end.
- Prints «Hello» without a newline. Doing «import sys» is a prerequisite. Needs a subsequent «sys.stdout.flush()» in order to display immediately on the user’s screen.
- Prints «Hello» with a newline.
- Prints to standard error stream.
- Prints to standard error stream.
- Prints a string that has been formatted with the use of an integer passed as an argument.
- Like the previous, just that the formatting happens outside of the print statement.
- Outputs «Float: 1.234». The number 3 after the period specifies the number of decimal digits after the period to be displayed, while 6 before the period specifies the total number of characters the displayed number should take, to be padded with spaces if needed.
- Passes two arguments to the formatter.
File Output [ edit | edit source ]
Printing numbers from 1 to 10 to a file, one per line:
With «w», the file is opened for writing. With «file=file1», print sends its output to a file rather than standard output.
Printing numbers from 1 to 10 to a file, separated with a dash:
Opening a file for appending rather than overwriting:
In Python 2.x, a redirect to a file is done like print >>file1, i.
See also Files chapter.
Formatting [ edit | edit source ]
Formatting numbers and other values as strings using the string percent operator:
Formatting numbers and other values as strings using the format() string method, since Python 2.6:
Formatting numbers and other values as strings using literal string interpolation, since Python 3.6:
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:
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:
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:
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(<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:
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:
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 instead of by the default single space:
To squish objects together without any space between them, specify an empty string ( «» ) as the separator:
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:
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:
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:
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.
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:
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-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:
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.
Python Input, Output and Import:

Until now our program was static, the values were defined to the variables. In some cases user might want to input values to variables, which allows flexibility. Python has input() function to perform this.
Input([string to be displayed on screen])
Here we can clearly see that python habitually takes the input value given by the user as a string. To convert this we can use int() or float() functions.
Using eval():
It can evaluate expression provided the input is a string.
Taking multiple inputs:
Using split():
This function helps in getting multiple inputs from the user. It breaks the given input by the specified separators. If there is no separator, any white space is considered to be a separator.
Using list comprehension:
List comprehension is commonly used to create list in python but it is also used in getting multiple inputs from users. []
Python Import:
When your program grows deeper, we cannot keep writing codes for each and every action we need to perform. So in real time, we break the program into different modules. Python has various modules and libraries. These modules contain python definitions and statements.
Definitions inside a module can be imported into another module or interactive interpreter in python. We use import keyword do perform this.
Now all the definitions inside math module are handy for us. When you need only a specific function then use from keyword.
Python Output:
To output data on the screen we use print() function.
print(*object, sep= “ ”,end=“ ”,file=sys.stdout,flush=False)
Output formatting using format():
To make your output look easy on the eye, you have to format the actual appearance of the output. This can be done using .format()