• 技术文章 >常见问题 >Python常见问题

    python如何从键盘输入数据?

    yangyang2020-05-19 11:23:32原创17130

    python从键盘输入数据的方法:

    在python中使用raw_input()、input()、sys.stdin等方法获取从键盘输入的数据。

    1、使用raw_input()函数获取从键盘输入的数据

    python raw_input() 用来获取控制台的输入。raw_input() 将所有输入作为字符串看待,返回字符串类型。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    >>>a = raw_input("input:")

    input:123

    >>> type(a)

    <type 'str'>              # 字符串

    >>> a = raw_input("input:")

    input:runoob

    >>> type(a)

    <type 'str'>              # 字符串

    >>>

    2、使用input()方法获取从键盘输入的数据

    input() 函数接受一个标准输入数据,返回为 string 类型。

    示例:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    >>>a = input("input:")

    input:123                  # 输入整数

    >>> type(a)

    <type 'int'>               # 整型

    >>> a = input("input:")   

    input:"runoob"           # 正确,字符串表达式

    >>> type(a)

    <type 'str'>             # 字符串

    >>> a = input("input:")

    input:runoob               # 报错,不是表达式

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

      File "<string>", line 1, in <module>

    NameError: name 'runoob' is not defined

    <type 'str'>

    3、使用sys.stdin方法获取

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    import sys

    try:

        while True:

            print('Please input a number:')

            n = int(sys.stdin.readline().strip('\n')) #strip('\n')表示以\n分隔,否则输出是“字符串+\n”的形式

            print('Please input some numbers:')

            sn = sys.stdin.readline().strip()#若是多输入,strip()默认是以空格分隔,返回一个包含多个字符串的list。

            if sn == '':

                break

            sn = list(map(int,sn.split())) #如果要强制转换成int等类型,可以调用map()函数。

            print(n)

            print(sn,'\n')

    except:

        pass

    更多Python知识请关注Python自学网

    专题推荐:python
    上一篇:python中怎样求行数? 下一篇:python如何把秒换成时分秒

    相关文章推荐

    • python怎么使用wmi?• python程序里rt是什么意思?• 20个Python代码实现的小例子!• 如何在python中获取调用图片的大小?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网