zoukankan      html  css  js  c++  java
  • 16.Python input()函数:获取用户输入的字符串

    input() 函数用于向用户生成一条提示,然后获取用户输入的内容。由于 input() 函数总会将用户输入的内容放入字符串中,因此用户可以输入任何内容,input() 函数总是返回一个字符串。

    例如如下程序:

    1. msg = input("请输入你的值:")
    2. print (type(msg))
    3. print(msg)

    第一次运行该程序,我们输入一个整数,运行过程如下:

    请输入你的值:2
    <class 'str'>
    2

    第二次运行该程序,我们输入一个浮点数,运行过程如下:

    请输入你的值: 1.2
    <class 'str'>
    1.2

    第三次运行该程序,我们输入一个字符串,运行过程如下:

    请输入你的值:Hello
    <class 'str'>
    Hello

    从上面的运行过程可以看出,无论输入哪种内容,始终可以看到 input() 函数返回字符串,程序总会将用户输入的内容转换成字符串。

    需要指出的是,Python 2.x 提供了一个 raw_input() 函数,该 raw_input() 函数就相当于 Python 3.x 中的 input() 函数。

    而 Python 2.x 也提供了一个 input() 函数,该 input() 函数则比较怪异:要求用户输入的必须是符合 Python 语法的表达式。通常来说,用户只能输入整数、浮点数、复数、字符串等。重点是格式必须正确,比如输入字符串时必须使用双引号,否则 Python 就会报错。

    使用 Python 2.x 来运行上面程序,假如输入一个整数,运行过程如下:

    请输入你的值:2
    <class 'int'>
    2

    使用 Python 2.x 来运行上面程序,假如输入一个复数,运行过程如下:

    请输入你的值: 2+3j
    <type 'complex'>
    (2+3j)

    使用 Python 2.x 来运行上面程序,假如输入一个字符串,运行过程如下:

    请输入你的值:Hello
    NameError : name 'Hello' is not defined

    上面程序报错的原因是:Python 2.x 的 input() 函数要求用户输入字符串时必须用引号把字符串括起来。

    在 Python 2.x 中应该尽量使用 raw_input() 函数来获取用户输入,因为 Python 2.x 中的 raw_input() 等同于 Python 3.x 中的 input()。

  • 相关阅读:
    Python 安装Twisted 提示python version 2.7 required,which was not found in the registry
    Openfire Strophe开发中文乱码问题
    css div 垂直居中
    How to create custom methods for use in spring security expression language annotations
    How to check “hasRole” in Java Code with Spring Security?
    Android 显示/隐藏 应用图标
    Android 当媒体变更后,通知其他应用重新扫描
    文件上传那些事儿
    专题:点滴Javascript
    主流动画实现方式总结
  • 原文地址:https://www.cnblogs.com/youqc/p/12066558.html
Copyright © 2011-2022 走看看