[파이썬] `sys.stdin`: 표준 입력

To use sys.stdin, you need to import the sys module at the beginning of your code:

import sys

Once you have imported the sys module, you can read input using the stdin object. Here is an example that prompts the user to enter their name and then prints it:

import sys

# Read input from the user
name = sys.stdin.readline()

# Print the entered name
print("Hello, " + name)

In the above code, we use the readline() method of sys.stdin to read the input from the user. The readline() method reads a line from input, including the newline character at the end. If you want to remove the newline character, you can use the strip() method.

import sys

# Read input from the user
name = sys.stdin.readline().strip()

# Print the entered name
print("Hello, " + name)

The strip() method removes any leading or trailing whitespace characters, including the newline character.

You can use sys.stdin to read multiple inputs as well. For example, if you want to read two numbers from the user and add them, you can do the following:

import sys

# Read the first number
num1 = int(sys.stdin.readline().strip())

# Read the second number
num2 = int(sys.stdin.readline().strip())

# Add the numbers
result = num1 + num2

# Print the result
print("The sum is:", result)

In the above code, we read two numbers from the user and convert them to integers using the int() function. Then, we add the numbers and print the result.

Using sys.stdin allows you to interactively read input from the user during runtime, making your programs more dynamic and versatile.