In the previous posts, we have covered basic concepts in Python. Now, it’s time to see some basic input and output through the command line in Python.

Output in Python

You’ve probably already learnt to print your output on the terminal by using the print() function. This section covers some further aspects of the print function and some basic formatting while printing output on the terminal.

Printing a blank line

You can just use print() without any arguments when you want to print a blank line on the terminal for better visibility.

Printing variables with formatting

Ever thought how can we print a variable along with a string? Let’s see an example.

The below program prints the addition of two variables on the command line in the following format: “Addition of <a> and <b> is: <result>” (Note: Text within the angle brackets (<>) indicates that the values will be printed.)

a = 2
b = 3
print("Addition of",a,"and",b,"is:",a+b)

You can see the properly formatted output in the image below: Program Output

Formatted strings

Python also supports formatted strings which could make the above task more easier and human readable.

Just put a f before the string and Python will treat it as a formatted string. Variable names in formatted strings are included within curly brackets ({}).

Considering the aforesaid example, the below program would return the same output:

a = 2
b = 3
print (f'Addition of {a} and {b} is: {a+b}')

The output would remain the same: Program Output

Further, numbers can be formatted by placing a colon (:) as a suffix to the variable name and specifying the required formatting. Some examples are given as under:

Formatted StringResult
{a:10d}Value of variable a up to 10 digits (Works for Integer data type only)
{a:.2f}Value of variable a rounded to 2 decimal places (For Float data type)
{a:3.2%}Value of variable a in percentage-format with two decimal places

Line-endings and separators

By default, the print() functions separates each new argument with a whitespace and ends each line with a new line. For example, print ("Hello","World") would print Hello World on the terminal and any print statement after this statement would be on a new line. This default behavior can be changed. Let’s see how:

Line-endings

To change line ending just set the value of end after you are done adding the output. For example, to end the line with a space, set end = ' ' in the print() function.

Separators

To change the separator between multiple values, set the value sep to the desired separator. For example, to separate multiple values with asterisk (*), set sep = '*' in the print() function.

Example

Let’s try the above concepts in a simple program:

print ("Hello", end = ' ')
print ("World", "Spam", sep = '*')
print ("Hello", "World", end = '/')
print ("Spam", "Hey", sep = '+', end = ':')  # Can be used together as well.

The output of the above code is shown below: Program Output

Input in Python

In Python, taking user-input from the command line is very simple. We use the input() function for the same.

Till now, we have been using hardcoded values for variables, but now we can assign values to variables at run-time using input() function.

Let’s take a simple program which accepts the user’s name and prints a greeting.

name = input()
print ("Hello",name)

The output of the above program would be as under: Program Output

But wait, how will the person running the program would know what is the expected input? To solve that the input() function allows you to supply prompts which are printed on screen before asking for input. Let’s modify the above program to get an idea of prompts:

name = input("Enter your name: ")
print ("Hello", name)

Now the output looks better:

Program Output

By default, any user input accepted by the input() function is returned as String (str). But wait, what if I want to input numbers. Well, Python has a solution for that as well.

Type Casting

Python supports type casting (or explicit type conversion in simple words) from one data type to another if it is within its powers (for anything which it does not understand or beyond its powers, it will throw an syntax error). You can convert String data type to Integer (int) or Float (float) if the String is a valid number.

To demonstrate type casting, let’s take a simple program which adds 2 numbers input by user (one is integer and other is float):

a = int(input("Enter an integer: "))
b = float(input("Enter a decimal number: "))
print (f"{a} + {b} = {a+b}")

The output of the above program would be as under: Program Output

Complete list and usage of type conversion functions is given as under:

FunctionDescription
int(x)Converts a string variable (say x) to an integer, provided the string is a proper number
int(x,b)Converts a string variable (say x) to an integer of the specified base. The string should be of the valid base in that case. Some of the recognized number systems and corresponding bases are given below this table.
float(x)Converts a string variable (say x) to a decimal number. The string should be a valid floating point number.
complex(x)Converts a string variable (say x) to a complex number having real and imaginary parts. Important: The operator separating the real and imaginary parts (+ or - sign) should not have any whitespace around it.
BaseNumber SystemExample
2Binary"010101" (21 represented in binary format)
8Octal"0o25" (21 represented in octal format)
10Decimal"21" (21 in decimal format. This is what int(x) form uses!)
16Hexadecimal"0x000015" (21 in hexadecimal format)

Summary

In this post, we learnt how we can format our output in a funky and human-readable manner as well as how we can accept input during run-time. Thanks for reading this post and hope that you learnt something valuable.