Python provides several ways to perform input and output operations.
Input in Python
There are several ways to read input from the user in Python.
input()
input()
function reads a line of text from the user and returns it as a string.
name = input("Enter your name: ") print("Hello, " + name + "!")
raw_input()
raw_input()
function (Python 2.x only) is similar to input()
, but returns the input as a string without evaluating it as an expression.
sys.stdin
sys.stdin
reads input from the standard input stream, which is usually the keyboard.
import sys for line in sys.stdin: print(line.strip())
Output in Python
There are several ways to display output to the user in Python:
print()
print()
displays a message to the user, followed by a newline character.
print("Hello, World!")
sys.stdout
sys.stdout
writes output to the standard output stream, which is usually the console.
import sys sys.stdout.write("Hello, World!\n")
logging module
It provides a way to log messages at different levels (e.g., debug
, info
, warning
, error
).
import logging logging.basicConfig(level=logging.INFO) logging.info("Hello, World!")
Command-Line Interface
Here’s an example of a simple command-line interface that reads input from the user and writes output to the console.
def main(): print("Welcome to My CLI!") while True: command = input("> ") if command == "quit": break elif command == "hello": print("Hello, World!") else: print("Invalid command. Try again!") if __name__ == "__main__": main()