Python Input and Output Functions

Updated: March 23rd, 2023, 09:47:32 IST
Published: March 23rd, 2023
Python Input and Output Functions
Title: Python Input and Output Functions

In Python, there are two very important functions that we use to interact with the user: input and output functions. These functions allow us to take input from the user and display output to the user on the console. The input function is used to receive input from the user, while the output function is used to display output on the console. In this article, we will discuss these two functions and their variations in simple terms.

Function Description
print() This output function is used to generate an output at the console.
input() This input function is used to read a line of input entered by the user at the console and returns it as a string.

In Python, there are several ways to take input from the user and display output to the user. Below are some examples of input and output in Python:

Input

1. Using the input() function:

The input() function is used to take input from the user. It reads a line of text entered by the user and returns it as a string.

Example:

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

Output:

Enter your name: John
Hello, John!

2. Using command-line arguments:

Command-line arguments are passed to a Python program using the sys.argv list. The first argument, sys.argv[0], is the name of the program itself.

Example:

import sys

name = sys.argv[1]
print("Hello, " + name + "!")

Command-line Terminal:

python program.py John

Output:

Hello, John!

Output

1. Using the print() function:

The print() function is used to display output to the user. It takes one or more arguments and displays them on the console.

Example:

print("Hello, World!")

Output:

Hello, World!

2. Using formatted strings:

Formatted strings allow you to embed values into a string using placeholders. The placeholders are denoted by curly braces {}.

Example:

name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output:

My name is John and I am 25 years old.

3. Using f-strings:

f-strings are a more modern way to format strings in Python. They allow you to embed values into a string using placeholders prefixed with the letter f.

Example:

name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:

My name is John and I am 25 years old.

In conclusion, Python provides different methods for input and output. Input can be taken from the user using the input() function or command-line arguments, while output can be displayed using the print() function or formatted strings like f-strings. These methods are flexible and can be used in various scenarios depending on the needs of the program.