The Wayback Machine - https://web.archive.org/web/20240927085356/https://www.geeksforgeeks.org/input-and-output-in-python/
Open In App

Input and Output in Python

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Understanding input and output operations is fundamental to Python programming. With the print() function, you can display output in various formats, while the input() function enables interaction with users by gathering input during program execution.

Python Basic Input and Output

In this introductory guide, we’ll explore the essentials of Python’s basic input and output functionalities, empowering you to efficiently interact with users and display information.

Print Output in Python

At its core, printing output in Python is straightforward, thanks to the print() function. This function allows us to display text, variables, and expressions on the console. Let’s begin with the basic usage of the print() function:

How to Print Output in Python

In this example, “Hello, World!” is a string literal enclosed within double quotes. When executed, this statement will output the text to the console.

Python
print("Hello, World!")

Output
Hello, World!

Print Single and Multiple variable in Python

The code assigns values to variables name and age, then prints them with labels.

Python
name = "Alice"
age = 30
print("Name:", name, "Age:", age)

Output
Name: Alice Age: 30

Format Output Handling in Python

Output formatting in Python with various techniques including the format() method, manipulation of the sep and end parameters, f-strings, and the versatile % operator. These methods enable precise control over how data is displayed, enhancing the readability and effectiveness of your Python programs.

Example 1: Using Format()

Python
amount = 150.75
print("Amount: ${:.2f}".format(amount))

Output
Amount: $150.75

Example 2: Using sep and end parameter

Python
# end Parameter with '@'
print("Python", end='@')
print("GeeksforGeeks")


# Seprating with Comma
print('G', 'F', 'G', sep='')

# for formatting a date
print('09', '12', '2016', sep='-')

# another example
print('pratik', 'geeksforgeeks', sep='@')

Output
Python@GeeksforGeeks
GFG
09-12-2016
pratik@geeksforgeeks

Example 3: Using f-string

Python
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Output
Hello, My name is Tushar and I'm 23 years old.

Example 4: Using % Operator

We can use ‘%’ operator. % values are replaced with zero or more value of elements. The formatting using % is similar to that of ‘printf’ in the C programming language.

  • %d –integer
  • %f – float
  • %s – string
  • %x –hexadecimal
  • %o – octal
Python
# Taking input from the user
num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)

Output

Enter a value: 50The sum is 55

Take Multiple Input in Python

The code takes input from the user in a single line, splitting the values entered by the user into separate variables for each value using the split() method. Then, it prints the values with corresponding labels, either two or three, based on the number of inputs provided by the user.

Python
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
 
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

Output

Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15

Take Conditional Input from user in Python

In this example, the program prompts the user to enter their age. The input is converted to an integer using the int() function. Then, the program uses conditional statements to check the age range and prints a message based on whether the user is a minor, an adult, or a senior citizen.

Python
# Prompting the user for input
age_input = input("Enter your age: ")

# Converting the input to an integer
age = int(age_input)

# Checking conditions based on user input
if age < 0:
    print("Please enter a valid age.")
elif age < 18:
    print("You are a minor.")
elif age >= 18 and age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

Output

Enter your age: 22
You are an adult.

Taking input in Python

Python input() function is used to take user input. By default, it returns the user input in form of a string. 

Syntax: input(prompt)

How to Take Input in Python

The code prompts the user to input their name, stores it in the variable “name”, and then prints a greeting message addressing the user by their entered name.

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

Output

Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!

How to Change the Type of Input in Python

By default input() function helps in taking user input as string. If any user wants to take input as int or float, we just need to typecast it.

How to Print Names in Python

The code prompts the user to input a string (the color of a rose), assigns it to the variable color, and then prints the inputted color.

Python
# Taking input as string
color = input("What color is rose?: ")
print(color)

Output

What color is rose?: Red
Red

How to Print Numbers in Python

The code prompts the user to input an integer representing the number of roses, converts the input to an integer using typecasting, and then prints the integer value.

Python
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)

Output

How many roses?: 8
8

How to Print Float/Decimal Number in Python

The code prompts the user to input the price of each rose as a floating-point number, converts the input to a float using typecasting, and then prints the price.

Python
# Taking input as float
# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)

Output

Price of each rose?: 50.30
50.3

Find DataType of Input in Python

In the given example, we are printing the type of variable x. We will determine the type of an object in Python.

Python
a = "Hello World"
b = 10
c = 11.22
d = ("Geeks", "for", "Geeks")
e = ["Geeks", "for", "Geeks"]
f = {"Geeks": 1, "for":2, "Geeks":3}


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

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
<class 'dict'>

Input and Output in Python – FAQs

What are Input and Output Files in Python?

In Python, input files are files from which a program reads data. These files can be text files, binary files, or any other data formats that the program needs to ingest and process. Output files are files to which a program writes data. This might include results, logs, or any processed data that the program needs to save for later use or to provide information to other programs or users.

What is the Difference Between Input and Output?

  • Input refers to data or signals received by a system or a process, which are then processed or used by the system to perform tasks or produce results. In computing, inputs can be user commands, data from files, network data, etc.
  • Output is the data or signals that a system or process sends out. It is the result of processing the input data. Outputs can be displayed on the screen, written to files, or sent over a network.

In the context of Python programming, input could be reading data from the keyboard, a file, or an external device, while output could be printing to the console, writing to a file, or sending data over a network.

What is Input Process Output in Python?

The concept of Input, Process, Output (IPO) in Python refers to a fundamental approach to programming:

  • Input: Gather data from external sources like user input, file systems, or external sensors.
  • Process: Perform computations or manipulate the data in some way.
  • Output: Display the results of the computations or store them for later use.

This model helps structure programs in a logical and clear manner, ensuring that data flows through the application in a manageable way.

How to Write Output in Python?

Writing output in Python can be done in several ways:

  1. Printing to the Console: Use the print() function to send output to the standard output (usually the console).Example:
  2. Writing to a File: Use Python’s file handling capabilities to write data to a file.Example:
  3. Using Standard Output Streams: For more control, you can use the sys.stdout to write directly to the standard output stream, which is useful for more complex console applications.Example:
print("Hello, World!")
with open('output.txt', 'w') as file:
file.write("This is some output data.")
import sys
sys.stdout.write("This is some output data.\n")

Each method of output is suited to different scenarios, from simple scripts to complex applications interacting with file systems and external interfaces



Previous Article
Next Article

Similar Reads

Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Different Input and Output Techniques in Python3
An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -> this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or decimal numbers n = float(input()) 2. Taking Multipl
3 min read
SciPy - Input and Output
In this article, we learn about SciPy input and output. In order to handle inputs and outputs of multiple formats, Scipy.io package provides multiple methods. Some of the formats that can be handled by the Scipy.io package are: MatlabNetcdfIDLArffMatrix MarketWave Among this Matlab is the format which is used very frequently. Now let's see the func
2 min read
Biopython - Sequence input/output
Biopython has an inbuilt Bio.SeqIO module which provides functionalities to read and write sequences from or to a file respectively. Bio.SeqIO supports nearly all file handling formats used in Bioinformatics. Biopython strictly follows single approach to represent the parsed data sequence to the user with the SeqRecord object. SeqRecord SeqRecord o
3 min read
Python | Testing Output to stdout
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper outp
2 min read
Python | Logging Test Output to a File
Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : import unittest class MyTest(unittest.TestCase): ... if __name__ == '__main__': unitt
2 min read
Python VLC MediaPlayer – Getting Audio Output Devices
In this article we will see how we can get list of output devices of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. Audio o
2 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
How to write the output to HTML file with Python BeautifulSoup?
In this article, we are going to write the output to an HTML file with Python BeautifulSoup. BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file. Modules needed and installation: pip install bs4 Approach: We will first import all the required libraries.Make a g
2 min read
Writing Scrapy Python Output to JSON file
In this article, we are going to see how to write scrapy output into a JSON file in Python. Using scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provided file name containing all scraped data. Note tha
2 min read
Click response on video output using Events in OpenCV – Python
OpenCV is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. In this article, we will create a program with a click response on video output using events in OpenCV Python library. We will be using “cv2.EVENT_LBUTTONDOWN” in case wh
3 min read
How to Disable Output Buffering in Python
Output buffering is a mechanism used by the Python interpreter to collect and store output data before displaying it to the user. While buffering is often helpful for performance reasons there are situations where you might want to disable it to ensure that output is immediately displayed as it is generated especially in the interactive or real-tim
3 min read
Python | Output Formatting
In Python, there are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values. Output Formatting in PythonThere are several ways to f
7 min read
Python | Output using print() function
Python print() function prints the message to the screen or any other standard output device. In this article, we will cover about print() function in Python as well as it's various operations. Python print() Function Syntax Syntax : print(value(s), sep= ' ', end = '\n', file=file, flush=flush) Parameters:  value(s): Any value, and as many as you l
8 min read
Retrieving the output of subprocess.call() in Python
The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Introduction
4 min read
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt )raw_input ( prompt )input() function Pytho
4 min read
Autocomplete input suggestion using Python and Flask
In this article, we will learn how to give features like auto-completion to the data that is passed from Flask. Autocomplete basically means predicting the rest of the word when the user types something. This way human interaction also increases with every correct prediction. Let's see how to do the same. We will be using jquery for autocompletion.
2 min read
Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python
In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy. Example: Input: [complex(np.nan,np.inf)] Output: [1000.+1.79769313e+308j] Explanation: Replace Nan with complex values and infinity values with large finite. numpy.nan_to_num method The numpy.nan_to_num method
3 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
Take input from user and store in .txt file in Python
In this article, we will see how to take input from users and store it in a .txt file in Python. To do this we will use python open() function to open any file and store data in the file, we put all the code in Python try-except block. Let's see the implementation below. Stepwise Implementation Step 1: First, we will take the data from the user and
2 min read
How to widen output display to see more columns in Pandas dataframe?
In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let's see how to widen output display to see more columns. Method 1: Using pandas.set_option() function. This function is used to set the value of a specified option. Syntax: pandas.set_option(pat, value) Returns:
2 min read
How to get Scrapy Output File in XML File?
Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population by country data from worldometers website. Let's i
2 min read
How to create CSV output in Flask?
In this article, we will see how to create a CSV output using Flask. Python and Flask Web Frameworks provide powerful tools to generate a report, export data and create catalogs. We will see how to generate both CSV files using Python and Flask. Creating CSV files in Python FlaskStep 1: InstallationWe are using Flask to create CSV output. Please re
3 min read
Django CSV Output
Generating CSV files in a Django web application can be achieved easily with the right libraries and a structured approach. By following the steps outlined in this article, you can provide users with the ability to download data in these popular formats, enhancing the usability and functionality of your Django application. Step to Create CSV Output
4 min read
How to generate basic HTML output using CGI scripts?
In this article, we will explore the process of generating basic HTML output using CGI scripts. Specifically, we will focus on creating a simple HTML web page using Python. The objective is to provide a step-by-step walkthrough, detailing the entire process of creating and utilizing CGI scripts to generate HTML content within a web environment. Wha
3 min read
Program to print its own name as output
Ever thought about writing a script which prints its own name when you execute it. It's pretty simple. You must have noticed programs in which the main function is written like this int main(int argc, char** argv) and you must have wondered what these 2 arguments mean. Well the first one argc is the number of arguments passed in to your program.The
2 min read
PyTest: Interactive Output instead of pure ASCII
There are numerous benefits of testing the code. It assures that modifications to the code won't result in regressions and boosts the confidence that the code acts as we anticipate. We should make the most of all the tools to make writing and maintaining tests as comfortable as we can because it is an exacting job. There are a number of different a
5 min read
Python | Find all close matches of input string from a list
We are given a list of pattern strings and a single input string. We need to find all possible close good enough matches of input string into list of pattern strings. Examples: Input : patterns = ['ape', 'apple', 'peach', 'puppy'], input = 'appel' Output : ['apple', 'ape'] We can solve this problem in python quickly using in built function difflib.
2 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks like this. Here we write a command and to execute
2 min read
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to get input a list from the user using Python. Example: Input : n = 4, ele = 1 2 3 4Output : [1, 2, 3, 4]Input : n = 6, ele = 3 4 1 7 9 6Output : [3, 4, 1, 7, 9, 6]Get a list as input from user in Python using Loop C/C++ Cod
2 min read
Article Tags :
Practice Tags :