zoukankan      html  css  js  c++  java
  • Python:raw_input()和input()区别

    函数:raw_input()和input()

    注意:在python3.x中,已经删除raw_input(),取而代之的是input(),当然这仅仅是重命名,用法还是一样。因此在这里介绍的是python2.x中的raw_input()和input(),在python3.x中只要按raw_input()的使用方式就行

    1:作用:读取控制台的输入与用户实现交互

    2:语法
    raw_input([prompt]) 
    input([prompt])

    3:参数
    prompt:如果存在此参数,则会直接输出到屏幕上,不会再往下另起一行

    4:两者关系:
    input()本质上是使用raw_input()来实现的,即调用完raw_input()之后再调用eval()函数,调用如下:
    def input(prompt):
        return (eval(raw_input(prompt)))

    5:两者相同点:
    都能接受字符串、数字以及表达式作为输入。

    6:两者差别:
    6.1、当输入为字符串时:
    raw_input(): 读取控制台的输入,同时返回字符串类型
    input():    读取控制台的输入,但输入时必须使用引号括起来,否则会报错

    6.2、当输入为纯数字时:
    raw_input(): 读取控制台的输入,同时返回字符串类型,当作字符串处理
    input():    读取控制台的输入,返回输入的数值类型(int, float)

    6.3、当输入为字符串表达式时:
    raw_input(): 读取控制台的输入,但不会对输入的数字进行运算,直接返回字符串类型,当作字符串处理
    input():    读取控制台的输入,对合法的 python 数字表达式进行运算,返回运算后的结果

    6.4、输入的为特殊字符时
    比如' ',' '等
    raw_input(): 读取控制台的输入,返回字符串类型,和输入一样
    input():    读取控制台的输入,但输入时必须使用引号括起来,返回特殊符号所代表的内容

    注:无特殊要求建议使用 raw_input() 来与用户交互

    7:实例:
    7.1、输入为字符串的时:

    >>> a1 = raw_input("raw_input_str: ")
    raw_input_str: hello
    >>> print a1,type(a1)
    hello <type 'str'>

    >>> a2 = input("input_str: ")
    input_str: hello
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        a2 = input("input: ")
      File "<string>", line 1, in <module>
    NameError: name 'hello' is not defined

    >>> a2 = input("input_str: ")
    input_str: 'hello'
    >>> print a2,type(a2)
    hello <type 'str'>

    7.3、输入为字符串表达式时:

    >>> c1 = raw_input("raw_input_exp: ")
    raw_input_exp: 3 + 3
    >>> print c1,type(c1)
    3 + 3 <type 'str'>

    >>> c2 = input("input_exp: ")
    input_exp: 3 + 3
    >>> print c2,type(c2)
    6 <type 'int'>

    7.4、输入的为特殊字符时:

    >>> d1 = raw_input("raw_input_sp: ")
    raw_input_sp:
    >>> print d1,type(d1)
    <type 'str'>

    >>> d2 = input("input_sp: ")
    input_sp:
    Traceback (most recent call last):
      File "<pyshell#57>", line 1, in <module>
        d2 = input("input_sp: ")
      File "<string>", line 1
       
        ^
    SyntaxError: unexpected character after line continuation character

    >>> d2 = input("input_sp: ")
    input_sp: ' '
    >>> print d2,type(d2)
     <type 'str'>

  • 相关阅读:
    nested exception is java.io.FileNotFoundException: class path resource [spring-mybatis.xml] cannot be opened
    jdbc批量插入实现大批量数据快速插入
    setInterval设置停止和循环
    在java中使用dom4j解析xml(示例代码)
    获取请求端的ip地址
    行为型之责任链模式
    行为型之策略模式
    行为型之命令模式
    行为型之模板方法模式
    结构型之门面模式
  • 原文地址:https://www.cnblogs.com/liunaixu/p/7811473.html
Copyright © 2011-2022 走看看