Data input and output in Python

by Alex
Data input and output in Python

All existing programs and applications interact with the user in one way or another. To do this, they receive data from the user, process it, and output something in response. There is no point in applications not interacting with the user. Python has built-in powerful tools for formatted input and output, enough to implement user interaction in a full-fledged application.

Obtaining data input

Receiving data is a critical component of any program. For example, a simple calculator receives data from the user when the user enters numbers on the keyboard, clicks on calculator interface elements, even pastes a copied expression. Input in Python 3 is usually stored in variables or lists so that it can be processed. The syntax of an input operation looks like this:

a = input()

If you execute this code interactively in IDLE the cursor will move to a new line and the program will wait for the input data to be written into the a variable. In addition, input() allows you to output some text before the input request, for example:

a = input("Enter your name")

This way you can hint to the user what to type. In contrast to strictly typed programming languages, Python allows you to input any type of data without explicitly specifying it. That is, the user can enter either a string or a number. The syntax of the input command will not change. However, it is often necessary to get data of a certain type, e.g., a calculator expects a number and the user enters a string. To do this, a type conversion is used, in this case to an integer type:

a = int(input("Enter an integer"))

If the user enters a string or a fraction, the Python interpreter will raise an exception. Therefore, the try-except statement is used for input:

a = int(input("Enter an integer"))
    print("Error, not an integer entered")

More about checking if an integer is entered can be found in a separate article. You can also call for input in an infinite loop, which is only exited when the user enters the correct type:

while True:
a = int(input("Enter an integer: "))
        print("You did not enter an integer, error")


Not only is print used to display data on the screen, but it can also be used to redirect the output of one program to the input of another, or to write the output to a file, etc. To display data in Python, we use the print() function. You can use it to print out strings, numbers, and sequences. Its syntax looks like this:



The Python interpreter also allows you to pass another function to print():

def sum(a, b):
    return a + b
print(sum(5, 2)) # prints 7

In this case, the sum function will calculate the sum of the arguments and return the result. This result will be printed to the console with print. Multiple arguments can be passed to print():

print("one", "two", 5) # Will print "one two 5"

Strings can also be added with the “+” operator:

print("one" + "two", 5) # Will print "one two 5"

It is not always necessary to print something on the screen, however. Programmers can redirect the output of a program to a file. The print() function has an optional “file” parameter that defaults to “sys.stdout”, which is the output to the screen. If the programmer wants to redirect the output to a file, he must write the code:

f = open("file.txt", "w") # Open file in write mode
print("String", file = f) # Output "String" to the file

In addition, if you want to make a nice colorful output, you can use the colorama or termcolor libraries. More details about color output are described in a separate article on this site.

A sample program

In programs, input and output are interrelated, for example, the user enters data, the program processes them and outputs back. Even if the program is not a console program, but a GUI, if the user clicked the “Run” button, he still entered data into the program, which gave the signal to perform a function. Here is an example of a console program that performs operations on numbers. That is, it performs data input and output to the console in Python 3. We enter two numbers and choose an operation to perform on them: add, subtract, multiply or divide. The program calculates the result and prints it out.

# Operations on two numbers
def sum(a, b):
    return a + b
def sub(a, b):
    return a - b
def mult(a, b):
    return a * b
def div(a, b):
    return a / b

def main():
    while True:
            #Enter numbers
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = int(input("Operation number:n1) +n2) -n3) *n4) /n"))
            print("Need to enter a number, try again ...n")
continue # Repeat the input, if it is not a number
        break # Quit if the numbers are correct
# Apply the correct operation according to the input
    cond = {1 : sum(a, b)
            2 : sub(a, b),
            3 : mult(a, b),
            4 : div(a, b)}
    # print the result of the operation

if __name__ == "__main__":

Here is an example of operation:

A sample programIn this way we have a console calculator. As it was written above, for beauty you can make the input and output colorful by changing the background color and the input characters. Also on our website is an example of a calculator with graphical interface. The Tkinter library was used for this.

Related Posts