How To Use Basic Input and Output in Python

Published On: Tue, 24 Dec 2024 Updated On: Tue, 24 Dec 2024

Understanding Basic Input and Output in Python

Python is a versatile and potent programming language that offers a user-friendly way to interact with the program through primary input and output functions. Input and output operations are fundamental building blocks of any programming language, such as asking for user input(s) in a program and printing informative message(s) as output.

Python provides straightforward methods to take user input and display output. And that's what you are going to learn in this discussion. I will specifically focus on how you can use the input() and print() functions. Additionally, you will also learn about string concatenation and formatting techniques to enhance the output presentation which greatly enhance the user experience in Text User Interface.

Taking User Input with input() Function

Your first question should be:

"Why does a program need user inputs?"

Although that is a very primitive question, it is very important. You need to understand that a program is a step by step instructions to do something. But on what? The answer is:

"The Data".

In Computer terminology, data can be anything such as numbers, strings, images and videos. Forgive me if I need to include any other type of data.

When you give this data to a program, program works on it based on the step-by-step instructions you have written in the program. For example, you want to write a program which does below calculation in sequence.

Code Example
num= 5
Add 10 into num and assign the answer into a new variable sum
Now multiply, the sum with 73 and store the answer into sum
Display the final sum to user as output.

The above steps are the step-by-step instructions which you want to perform on the num variable. Let's write a Python program for it and see how it looks like.

Code Example
num = 5
sum = num + 10
sum = sum * 73
sum

Okay, you must have understood it this simple program but what if you want to ask the program to use any number instead of just '5' everytime you run the program. The program should itself ask you to enter the number. Isn't it? Now you have a new question popped up in your genious mind.

"How can we provide these data into a program?"

Python provides the input() function that enable you to receive and store user input from the console. The input() takes a prompt as an optional argument and returns the user's entered value.

Note: input() stores the value in string datatype. Therefore, you need to explicitly take care of the necessary data type conversion.

Let's look at the above simple example again:

Code Example
num = input("Enter any number: ")
# Do you remember? input() stores value in
# string datatype therefore, we need to convert
# it to integer. We can use builtin int() to
# convert it as below. It will throw an error otherwise.
num = int(num)
sum = num + 10
sum = sum * 73
# Now let's display the final answer to user
print(sum)

Printing Output with print() Function

In the above example, the last line displays the output using the print() function. It can take multiple arguments separated by commas and print them with a space in between by default. Here's another example:

Code Example
age = 25
print("Your age is ", age)

# displays "Your age is 25" on console/terminal

But this is very simple. It displays message followed by the age value. But what if you want to present it beautifully so that it is easy to read on a console or a terminal? But before that let's see what other things print() function can do.

print() function accepts several parameters when we call it.  The first one is the positional parameters generally known as *args. Those we have seen just now. Every value you pass in print() will be displayed on console. So, in our last example, "Your age is " and age are the positional parameters.

Another set of parameters are **kwargs. It is nothing but the keyword parameters in key=value pair. Those are below:

object(s)

Prints the values to a stream, or to sys.stdout by default.

Any object, and as many as you like. will be converted to string before printed.

sep Optional. String inserted between values. Default is space.
end Optional. String appended after the last value. Default is newline \n.
file Optional. A file like object (stream); Defaults to sys.stdout.
flush Optional. Whether to forcibly flush the stream. Default is False.

I want you to explore these more, and if you find any difficulty, ask in the comments.

Formatting Output for Better Readability

Python provides different methods for formatting output, making it more presentable and easy to read. There are three main formatting options from which you can choose. Remember, it does not matter which one you choose. You just need to keep it consistent throughout your program. Consistency defines your personality as a programmer. Let's start with the first one.

String Concatenation

String concatenation is a simple technique that combines strings using the "+" operator. It is useful when displaying messages that include variables. Here's an example:

Code Example
name = "Alice"
age = 30
message = "Hello, " + name + "! You are " + str(age) + " years old."
print(message)

In Python, everything is an object and string is object as well. Hence, when the string is added to another string using + operator, it actually appends second string to the first string. Behind the scene, it is applyinh the concept of the operator overloading in Object Oriented Programming(OOP). Therefore, the + becomes the concatenation operator in case of strings.

Interview Question 2:

What is a concatenation operator in Python?

Now, you know the answer already.

Using format() Method

The format() Method is another approach to format strings. It uses curly braces as placeholders and is widely used for complex formatting. Here's an example:

Code Example
item = "book"
price = 19.99
message = "The {} costs ${:.2f}.".format(item, price)
print(message)

Did you notice the format specifier in second value(${:.2f})? Provide your comments if you what this signifies and what do you understand by it.

Interview Question:

How can we format the floating point numbers to display only 2 digits in precision in Python?

I want the answer from you so try this code in your machine and comment your answer.

Using f-strings (Formatted String Literals)

Python 3.6 introduced f-strings, which provide an elegant and readable way to format strings. They allow us to embed expressions inside curly braces, making code concise and readable. Let's see how to use f-strings:

Code Example
name = "Bob"
age = 28
message = f"Hello, {name}! You are {age} years old."
print(message)

Conclusion

We discussed about Python's primary input and output functions and how to use them in your program(s). We explored the input() function to take user input and display output on the console. Additionally, we digged into string concatenation and formatting techniques using f-strings and the format() method. These simple yet powerful techniques enhance the readability and presentation of the output in Python programs, making it easier for developers and users. Applying and practicing these concepts can elevate your Python programming skills and create more interactive and user-friendly applications.

How To Use Basic Input and Output in Python

Reader Comments


Add a Comment