Python Input Function and Print Function

All programming languages deal with inputs and outputs. A user necessarily has to interact with his program by passing some input to provide some output result. For the python programming language, the program receives python input from the user, transforms them through some algorithm to return some output. 

Inputs can come in various shapes or forms. The most common way from your keyboard. The program may as well receive input from a file on your machine or a database from the web. Similarly, outputs are displayed on the console of your IDLE, on the monitor screen using Graphics User Interface (GUI), dialog boxes or from external sources on the web. 

But how do you hardcode your program to receive input and display the output? This is the fundamental of programming. 

In this tutorial, we will be going down to the bolts and nuts of Python inputs and outputs. Helping you understand how to interact with a python program to display your desired results. 

By the end of this tutorial, you will specifically learn how to use the built-in python input() function to  take inputs from your keyboard. In addition, you will understand how to use the print() function to display the output of your program. Finally, you will discover how to use string formating techniques to personalize displayed output. 

Without further ado, let’s get started. 

Reading Input From the Keyboard

The easiest and commonest way for a program to receive data from the user is from the keyboard. The python input() function is a built-in function that helps to receive the data from the user to be used later by the program. 

To understand how the input function works, let’s start with its syntax from the official documentation

input([<prompt>])

Reads a line of input from the keyboard.

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

When your program executes your code and parses the input function, the program execution pauses and prompts you to type in some input with your keyboard. Upon typing your input and pressing the enter button, the program converts all the characters typed to a string format and goes on with the program execution. Let’s take some examples. 

#recieve some input from the user and store it in a variable called text
>>> text = input()
You are learning to use the input function
#print the data typed in by the user
>>> print(text)
You are learning to use the input function

In the example above, notice we did not pass any argument when calling the input function. You may decide to pass an argument called prompt. The prompt is displayed on the screen and is aimed at guiding the user on what is expected to be typed. If for instance, you want the user to type his first name, surname and age respectively, it is good practice to pass the instruction as an argument in string format. 

#prompt user to enter his first name, surname and age
first_name = input('Enter your first name: ')
surname = input('Enter your surname: ')
age = input('Enter your age: ')

#print the inputted first name, surname and age
print(first_name, surname, age)

Output:


>>>Enter your first name: James
>>>Enter your surname: Khan

>>>Enter your age: 31

James Khan 31

It is imperative to point out that the input function always returns a string to the program. It means that whatever computations you’ll be doing with the returned data will be treated as a string. 

The Python User Input Seen as Strings

In the last code example, we requested the user’s age which is expected to be a numeric value. The input function actually converts it to a string.  Let’s say our goal was to determine the user’s year of birth from his age. We will need to subtract his age from the present year. However, since the input function returns a string we cannot subtract an integer from a string. Attempting this will return an error from the program. See an illustration in the block of code below. 

#prompt user to enter his first name, surname and age
first_name = input('Enter your first name: ')
surname = input('Enter your surname: ')
age = input('Enter your age: ')

#print the inputted first name, surname and age
print(first_name, surname, age)

#subtract his age from the year 2020 to get his year of birth
year_of_birth = 2020 - age 

#print the year of birth
print(year_of_birth)

Output:

>>>Enter your first name: James

>>>Enter your surname: Khan

>>>Enter your age: 31
James Khan 31
Traceback (most recent call last):

  File "<ipython-input-3-16fade6153d5>", line 9, in <module>
    year_of_birth = 2020 - age

TypeError: unsupported operand type(s) for -: 'int' and 'str'

How do we remedy this? It’s simple.  If you desire to have your returned data in other data types apart from a string, you can make this datatype conversation by typecasting. 

Typecasting the Input Function

Typecasting helps you convert one datatype to another. You can use typecasting to convert the string datatype that the input function returns to any other datatype of your choice. You will need to enclose the input function variable in the datatype you decide, whether int, float, or other complex built-in functions. Let’s see an example. 

#prompt user to enter his first name, surname and age
first_name = input('Enter your first name: ')
surname = input('Enter your surname: ')
#typecast this age variable to an integer
age = int(input('Enter your age: '))

#print the inputted first name, surname and age
print(first_name, surname, age)

#subtract his age from the year 2020 to get his year of birth
year_of_birth = 2020 - age 

#print the year of birth
print(year_of_birth)

Output:

>>>Enter your first name: James

>>>Enter your surname: Khan

>>>Enter your age: 31
James Khan 31
1989

This code runs successfully, printing his year of birth to be 1989. And that’s because we converted the age variable from a string (by default) to an integer.

There is however another method of carrying out numerical computations of the python input argument without typecasting. If you pass a mathematical expression as the input function argument, say (2+3),  although the returned object will be in string function, you can evaluate the expression using the eval() function. The eval() function sees the argument as an expression that can be evaluated and attempts to do so. Let’s evaluate a mathematical operation using the eval() function. 

#this program illustrates how to use the eval() function
#enter some mathematic computation
var = input('Enter some numerical computation: ')
#evaluate and print the result
eval(var)

Output:

>>>Enter some numerical computation: 2 + 3
5

Note that the examples thus far are with the python 3 version. In python 2, the input and eval function behaves slightly different.

Variations of the Python Input Function in Python 2 and Python 3 Versions

If you’re using a Python 2 version, there are slight differences in the way the input function operates. In python 2, there is a function called the raw_input() function alongside the input function. The raw input function behaves like the input () function in python 3. The raw input function in python 2 takes an input from the user through the keyboard and converts the input to a string. 

The python 2 version nevertheless has the input function. The input function in python 2 however behaves like the eval function in python 3. In other words, the input function in python 2 attempts to evaluate the computation passed as an argument to the function.  It is important to take note of this especially if you have python 2 installed on your machine. 

Writing Output to the Console

While we have discussed how to feed inputs from the user to the program, we need to equally discuss how to display output from the program to the user. You can do this with the print() statement (now a function in python 3). We begin with its syntax. 

Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

From the syntax, it’s clear that the print function allows you to print more than one object. Commas separate the objects. By default, the print function, when displaying the result, adds a space after the last character of each object and appends a new line at the end of the characters. You can tweak these behaviors with the argument passed which we will discuss shortly. 

Let’s see a simple example of the print() function. 

#print each string on the same line
print('I', 'am', 'learning', 'python', 'programming')

Output:

I am learning python programming

You can pass all kinds of objects type on the print function. The object could a string, integer, floating-point numbers, or Boolean. They could also be lists, dictionaries, sets, etc.

#create variables of different types
a = 'Khan'
b = 2
c = True
d = [1, 2, 3, 4]
e = ('a', 'b', 'c')

#print the defined variables
print(a, b, c, d, e)
#print the types of each variable

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

Output:

Khan 2 True [1, 2, 3, 4] ('a', 'b', 'c')
<class 'str'>
<class 'int'>
<class 'bool'>
<class 'list'>
<class 'tuple'>

Let’s now see how we can adjust how the print function behaves by tweaking its arguments.

Changing the Print Function Keyword Argument

Arguments in python can be classified into 2: positional arguments and keyword arguments. When passing arguments to a function, the official documentation specifies how each of the arguments are arranged. If you decide to use positional arguments, you must arrange your argument as per how it is arranged in the official documentation. Misplacing the position of the argument can and will mess up your code.

Using keywords arguments is a safer method. The keywords are clearly stated before it’s values. Keyword arguments are in the form <keyword>=<value>. If you are keyword arguments, you can rearrange the argument however you want. But then, note that when using positional arguments and keyword arguments, the positional arguments must be defined first, before the keyword argument. 

With the print function, the object you want displaying is the first argument you pass. Keyword arguments can then come afterward. There is a myriad of arguments you can define with the print function but we’d limit ourselves to the commonly used ones. 

The sep= Keyword Argument

The sep argument allows you to specify how you want the objects to be separated. By default, space separates each argument. If you need to change it to another character, define the character with the sep argument. You can pass any string for which the objects will be separated. Let’s see some examples.

#print the Apple, Orange Banana with the spaces
print('Apple', 'Orange', 'Banana')

#print Apple, Orange, Banana separated by a forward slash
print('Apple', 'Orange', 'Banana', sep='/')

#print Apple, Orange, Banana separated by a comma
print('Apple', 'Orange', 'Banana', sep=', ')

#print Apple, Orange, Banana with no space at all
print('Apple', 'Orange', 'Banana', sep='')
Apple Orange Banana
Apple/Orange/Banana
Apple, Orange, Banana
AppleOrangeBanana

In the first instance, we printed the strings with the default print argument. The strings were separated by spaces. To specify what character to separate the string, use the sep argument as seen above. If you do not want any separation at all, define the sep argument with an empty string.

The end= Keyword Argument

By default, when you use multiple print statements, each print statement ends on a new line. You can however change this setting to some other character you wish. If we want each print statement to send when a full stop, we will assign a full stop to the end argument. Check the example below.

#end the print statement with a new line
print('Apple', end='\n')
#end the print statement with a forward slash
print('Apple', end='/')
#end the print statement with a tab
print('Apple', end='\t')
#end the print statement with a comma
print('Apple', end=', ')

Output:

Apple
Apple/Apple     Apple,

Output Formatting

You may need to format the output of your print statement so it’s more understandable. One easy way to accomplish this is by using the str.format() method. The string objects are inserted normally with “”. Whereas, curly braces {} are used to enclose the defined variables are enclosed in curly braces. The curly braces are called placeholders. For better comprehension, let’s see how this is implemented.

#define some fruits named fruit_1 and fruit_2
fruit_1 = 'apples'
fruit_2 = 'oranges'
#print the fruits using string formatting method 
print('The boy loves {} so much but hate {}'.format(fruit_1, fruit_2))

Output:

The boy loves apples so much but hate oranges

You can specify how you want the strings to be ordered by passing the strings as a tuple. The index of the tuple is used to specify the order of the string formatting.

#define some fruits named fruit_1 and fruit_2
fruit_1 = 'apples'
fruit_2 = 'oranges'
#print the fruits using string formatting method 
print('The boy loves {1} so much but hates {0}'.format(fruit_1, fruit_2))
print('The boy loves {1} so much but hates {1}'.format(fruit_1, fruit_2))

Output:

The boy loves oranges so much but hates apples
The boy loves oranges so much but hates oranges

Let me explain how the above code works. Because, fruit_1 was the first argument in the .format method, it has index 0. The subsequent argument is of index 1. With this, you can now specify the exact variable you want in the placeholders using their index.

One new approach that has gained wide popularity is the use of f-stings. It’s available in python 3 alone but can carry out very complex string formatting easily. When using f-strings, f is typed before the opening and closing apostrophe for the string. The placeholders are placed inside the strings as against the previous approaches where they were used as argument for the .format() method

#define some fruits, named fruit_1 and fruit_2
fruit_1 = 'apples'
fruit_2 = 'oranges'
#print the fruits using string formatting method 
print(f'The boy loves {fruit_1} so much but hates {fruit_2}')

Output:

The boy loves apples so much but hates oranges

Conclusion on Python Input Function

In this tutorial, you have discovered how the two way communication between the program and the user works. Specifically, you have learnt how to use the python input function to receive input from the user and the print function to display output from the program. 

In addition, you learned how to display the output in an appealing manner using the various string formatting styles and particularly f-strings.

Leave a Comment

Pin It on Pinterest