目次
1. Introduction
When creating programs in Python, “standard input,” which processes user input, is extremely important. By using theinput()
function to get data from the keyboard, you can enable interaction with users. This article is designed for Python beginners, explaining the basics of standard input to advanced techniques with practical examples. You will learn step by step, from simple programs to more complex input handling.2. Basics of Using Standard Input in Python
2.1 What is the input()
function?
The input()
function receives input from the user and returns it as a string. For example, the following code gets the user’s name and prints it:name = input("Please enter your name: ")
print(f"Hello, {name}!")
In this code, the name entered by the user is stored in name
using input()
, and then a greeting message is displayed.2.2 Numeric Input and Type Conversion
Since the data obtained withinput()
is a string, you need to convert it using int()
or float()
to handle it as a number.age = int(input("Please enter your age: "))
print(f"You are {age} years old.")
In this example, the string is converted to an integer, and the age is output as a number.
3. Handling Multiple Lines of Standard Input
3.1 Multiple Line String Input
If you want to receive multiple lines of input, using afor
loop or list comprehension is efficient. For example, here’s code to let the user enter three different words:words = [input(f"Enter word {i+1}: ") for i in range(3)]
print(f"Entered words: {words}")
This code stores three lines of input in a list and outputs them.3.2 Multiple Inputs Separated by Spaces
When entering multiple values in a single line, you can use thesplit()
function to separate them by spaces. The following example asks the user to enter numbers separated by spaces and then converts them into integers:numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
print(f"Entered numbers: {numbers}")
Here, the map()
function converts the entered values into integers. The split()
method efficiently stores space-separated inputs into a list.4. Advanced Input: Handling Files and Binary Data
4.1 Using sys.stdin
for Standard Input
By using sys.stdin
, you can directly read data from standard input. This is useful when handling large text data or when the contents of a file are passed via command line input.import sys
data = sys.stdin.read()
print(f"Received data: {data}")
This code reads all data from standard input and outputs it.4.2 Simple Binary Data Handling
By usingsys.stdin.buffer
, you can directly process binary data. This is effective when working with images or files in binary format.import sys
binary_data = sys.stdin.buffer.read()
print(binary_data)
This code reads binary data from standard input and outputs it as-is.
5. Practical Use Cases: Problem-Solving with Standard Input
5.1 Average Calculation Program Using Standard Input
The following program takes integers from standard input, calculates their average, and outputs it. Such processing is often used in competitive programming and data processing:N = int(input("Enter the number of values: "))
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
average = sum(numbers) / N
print(f"The average is {average}.")
This program first receives the number of values, then treats space-separated input as a list, and calculates the average.5.2 Program to Receive Input Until Termination
This program continues to receive input until the user enters a blank line. By setting a termination condition, you can handle long-term input processing:data = []
while True:
line = input()
if line == "":
break
data.append(line)
print("Entered data: ", data)
In this example, data is collected until a blank line is entered, and all data is output at the end.6. Common Errors and How to Handle Them
6.1 Handling ValueError
When expecting numeric input, if the user mistakenly enters a string, a ValueError
occurs. To prevent this, you need to add input validation code:try:
age = int(input("Please enter your age: "))
except ValueError:
print("Invalid input. Please enter a number.")
6.2 Handling EOFError
When receiving multiple lines of input, an EOF (End of File) error may occur to indicate the end of standard input. To avoid this, it’s important to set proper termination conditions:import sys
for line in sys.stdin:
if line.strip() == "":
break
print(line.strip())
7. Conclusion
By using standard input in Python, you can easily create user interaction and develop more advanced programs. From the basicinput()
function to handling files and binary data, we covered various methods. Understanding and practicing the use of standard input improves both flexibility and efficiency in programming.