How to read input in python

下次还敢
Release: 2024-03-29 06:06:02
Original
926 people have browsed it

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

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>
Copy after login

where prompt is an optional prompt message that will be displayed when the user needs to input.

Example:

<code class="python">name = input("请输入您的姓名:")</code>
Copy after login

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>
Copy after login

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>
Copy after login

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

  • Input is always returned as a string, even if you expect it to be a number. If you need an integer or float, you need to cast it to the appropriate type:
<code class="python">age = int(input("请输入您的年龄:"))</code>
Copy after login
  • To read from multiple lines of input, you can use lines = sys. stdin.readlines() function, which returns each line as a list as a string:
<code class="python">lines = sys.stdin.readlines()</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template