Python Input and Output - Important Points
Python Input and Output refers to the process of reading and writing data from and to different sources such as files, console, network, etc. Understanding Input and Output is essential for every programmer as it is an integral part of any programming language. In this write-up, we will cover all the important aspects of Python Input and Output that beginners should know.
Input in Python: In Python, input() function is used to take input from the user. This function reads the input as a string and we can convert it to other data types as per our requirements. Let's see an example:
name =
input(
"Enter your name: ")
(
"Hello "+ name)
In the above code, input() function takes the input from the user and stores it in the variable name
. Then, the print() function prints the message along with the value of name
.
Output in Python: In Python, the print() function is used to output data to the console. We can pass multiple arguments to the print() function, which will be printed to the console separated by a space. Let's see an example:
name =
"John"
age = 25
(
"Name:", name,
"Age:", age)
In the above code, the print() function is used to output the name and age of a person to the console.
File Input and Output: Python provides several ways to read and write data from and to files. We can use the built-in open() function to open a file and read or write data to it. The open() function takes two arguments, the first one is the file name and the second one is the mode in which we want to open the file. Let's see an example:
# Opening a file in read mode
file = open(
"example.txt",
"r")
# Reading data from the file
data = file.read()
# Closing the file
file.close()
# Printing the data
print(data)
In the above code, we opened a file named "example.txt" in read mode, read the data from the file using read() function and printed it to the console. We then closed the file using close() function to release the resources.
We can also write data to a file using the write() function. Let's see an example:
# Opening a file in write mode
file = open(
"example.txt",
"w")
# Writing data to the file
file.write(
"This is an example file")
# Closing the file
file.close()
In the above code, we opened a file named "example.txt" in write mode, wrote the data "This is an example file" to the file using the write() function and closed the file.