Python3 读取键盘输入数据
Python3,读取,键盘输入,数据
2025-04-01 16:27:51 时间
input 输入
Python3
提供了 input()
内置函数从标准输入读入一行文本,默认的标准输入是键盘。input 可以接收一个 Python 表达式作为输入,并将运算结果返回。注意 input 函数从键盘输入中读取一行,将其转换为字符串 str
类型(带末尾的换行符),然后将其返回。实例代码运行结果如下所示。
但是,在 Jupyter Notebook 中运行得结果却不一样,我还没有找到原因。
input()
函数在Python3.8 中的解释如下,用法详情可参考此链接。
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline)
, and returns that. When EOF is read, EOFError is raised. Example:
读取多行多个数据
第一行输入两个数 n
、 m
,表示输入输入数据是 n 行 m 列的二维数组,接下来输入二维数组的具体元素,并保存在名为 matrix
的列表类型中。Python 输入多行多个数据的方法很灵活多样,方法一使用 sys.stdin.readline()
方法,代码如下:
代码图
def input_matrix():
# 第一行输入两个数 n、 m,表示输入输入数据是 n 行 m 列的二维数组
matrix = list()
input1 = sys.stdin.readline().strip().split(' ')
m, n = input1[0], input1[1]
for i in range(int(m)):
value = list(map(int, sys.stdin.readline().strip().split(' ')))
matrix.append(value)
print("打印保存的输入数据:")
print_lists(matrix)
if __name__ == "__main__":
input_matrix()
程序运行结果如下:
读取一行多个数据
使用 list()
创建数组存储数据,第一行输入一个数 m,表示输入输入数据是 m 大小的一维数组,输入数据使用 input()
函数,代码如下:
def input_vector():
num = int(input()) # 输入的一维向量数据总共有 num 个数
print("pleas input %d number" % num)
# 方法1 使用readline() 函数读取一整行数据,然后 split
vector = list(map(int, sys.stdin.readline().strip().split(' ')))
# # 方法2 使用 input 函数读取输入
# vector = [int(i) for i in input().split()]
print("打印保存的输入一整行数据:")
print_list(vector)
return vector
程序运行结果如下:
参考资料
相关文章
- python3获取Elasticsearch数据库数据
- python3.x默认使用UTF-8编码_pycharm怎么debug
- 关于Python3的import问题(pycharm可以运行,命令行import错误)
- python3.6写一个http接口服务,给别人调用1
- ROS中cv_bridge如何用python3进行编译
- python3 三种字符串(无前缀,前缀u,前缀b)与encode()「建议收藏」
- 失控的 Python3 类型
- python3.8安装matplotlib_matplotlib画图
- pycharm如何创建新项目_Python3
- tensorflow pycharm教程_tensorflow支持python3.8吗
- python3中pygame安装过程(超级详细)
- pycharm怎么设置编码格式_python3设置编码为utf8
- pycharm安装python3.6_python安装教程
- python2 和 python3 常见差异及兼容方式梳理
- centos 安装python3导致yum报错
- pycharm配置tensorflow环境_python3.6对应的tensorflow版本
- 大整数乘法python3实现
- 无法安装python3的连续报错-mysql include软链接问题
- win10系统下pycharm2017配置opencv-python3.4.5[通俗易懂]
- qpython3安装pygame_详解Python pygame安装过程笔记