# 4.3 输入

并不是所有程序都像我们前面所讲的那样，仅仅使用代码内部定义的输入数据，就可以使程序正确运行并得出满意的结果了。在一些特殊情况下，我们需要人为对数据输入源进行定义。常用的输入函数有Input，sys.stdin.readline()。下面我们对这两种函数展开介绍。

### 4.2.1 input()

Input函数的一般语法如下：

input(\[prompt])\
Input函数以string类型接收一个标准输入数据，并使用string类型将这个数据返回。

Input函数常与赋值语句连用来从键盘接受数据赋值给变量。

例

\>>>num=input(“我已经使用python\_年了！“)

我已经使用python\_年了！100 #输出提示内容后键入数值，此处键入100

\>>>num

‘100’ #输出为string类型100

### 4.2.2 sys.stdin

sys.stdin是一个标准化输入的模块。

使用sys.stdin.readline函数会将标准输入全部获取，包括末尾的换行符’\n’， 并使用string类型将这个数据返回。而input函数返回的数据中不包括换行符。

下面我们通过一个例子来分析input和sys.stdin.readline返回数据的差别。

\>>>import sys

\>>>s1=sys.stdin.readline()

\>>>s2=input()

\>>>len(s1), len(s2)

(13, 12)

字符串s1的长度为13，而s2的长度为12，这是因为s1在读取输入的时候，将键入的换行符保存了起来。而input没有这么做。可以使用strip函数将’\n’去掉，也可以使用\*\*\[:-1]\*\*去掉换行符。\[:-1]作用于序列类型，可将本序列的最后一个字符去除，保留剩余字符。

\>>>s3=sys.stdin.readline().strip(‘\n’)

\>>>s4=sys.stdin.readline().\[:-1]

\>>>s3, s4

(s3, s4)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://johannesliu.gitbook.io/data-science-python-implemented/4.0-practice/4.3-input.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
