In Python, there are two ways to read input: The input() function accepts a prompt and returns a string entered by the user. The sys.stdin.readline() function reads a line of text (including newlines) from standard input and returns a string.
How to read input in Python
There are two main ways to read input in Python: input()
function and <code>sys.stdin.readline()</code> function.
1. input() function
input()
The function gets input from the user and returns it as a string. Its syntax is as follows:
<code>input(prompt="")</code>
where prompt
is an optional prompt message that will be displayed when the user needs to input.
Example:
<code class="python">name = input("请输入您的姓名:")</code>
2. sys.stdin.readline() function
sys.stdin. The readline()
function reads a line of text (including newlines) from standard input and returns it as a string. Its syntax is as follows:
<code>sys.stdin.readline()</code>
Unlike the input()
function, the <code>sys.stdin.readline()</code> function does not accept prompt messages.
Example:
<code class="python">import sys name = sys.stdin.readline()</code>
Select method
input()
function is more suitable for prompting the user In the case of input, the <code>sys.stdin.readline()</code> function is more suitable for reading input from a script or other program.
Other Notes
<code class="python">age = int(input("请输入您的年龄:"))</code>
lines = sys. stdin.readlines()
function, which returns each line as a list as a string: <code class="python">lines = sys.stdin.readlines()</code>
The above is the detailed content of How to read input in python. For more information, please follow other related articles on the PHP Chinese website!