Python I O and import
Python provides several ways to perform input/output (I/O) operations. The most common ways of reading input and writing output in Python are through the use of input() and print() functions.
The input() function allows you to read a string from the user, which can be used in the program:
name = input("Enter your name: ")
print("Hello, " + name + "!")
The print() function allows you to display output to the console:
print("Hello, world!")
You can also use string formatting to include variables in your output:
x = 5
y = 10
print("The sum of {} and {} is {}".format(x, y, x + y))
Python also provides ways to read and write to files using the open() function:
# Writing to a file
with open("myfile.txt", "w") as f:
f.write("Hello, world!")
# Reading from a file
with open("myfile.txt", "r") as f:
content = f.read()
print(content)
Finally, you can also import modules and libraries in Python to extend the functionality of your program. You can use the import statement to import a module or library:
import math x = math.sqrt(25) print(x)
You can also import specific functions or variables from a module using the from keyword:
from math import sqrt x = sqrt(25) print(x)
Python comes with a large standard library, and there are also many third-party libraries available for specific tasks, such as data analysis, machine learning, web development, and more.
