Python Input and Output
Input and output are essential for any programming language, and Python is no exception. Input allows you to interact with the user, and output allows you to display data to the user.
The input()
function is the most basic way to read input from the user. It takes a prompt as its argument, and it returns the user’s input as a string. For example, the following code prompts the user to enter their name, and then it prints their name to the console:
name = input("What is your name? ")
print("Hello, {}!".format(name))
The print()
function is the most basic way to write output to the console. It takes a sequence of objects as its argument, and it prints the objects to the console. For example, the following code prints the string “Hello, world!” to the console:
print("Hello, world!")
The print()
function can also be used to format the output. For example, the following code prints the name of the user in uppercase letters:
name = input("What is your name? ")
print("HELLO, {}!".format(name.upper()))
In Python, you can use files to read and write data. The open()
function opens a file, and the read()
and write()
functions read and write data to the file. The with
statement ensures that the file is closed properly, even if an error occurs. For example, the following code opens a file called my_file.txt
, reads the contents of the file into a list, and then prints the contents of the list to the console:
with open("my_file.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line)
The read()
function reads the entire contents of the file into a string. The readlines()
function reads the contents of the file into a list of strings, where each string is a line in the file. The write()
function writes the data to the file.
The pathlib
module provides a more object-oriented way to work with files. It provides classes for representing files and directories, and it provides methods for interacting with files and directories. For example, the following code uses the pathlib
module to read the contents of a file called my_file.txt
and then print the contents of the file to the console:
from pathlib import Path
path = Path("my_file.txt")
if path.is_file():
with open(path, "r") as f:
lines = f.readlines()
for line in lines:
print(line)
else:
print("The file does not exist.")