关于python的input和raw_input(仅针对python2)

1. 先上官方帮助文档中的说明

input(...)     
    input([prompt]) -> value         
    Equivalent to eval(raw_input(prompt)).

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

2.通过上述文档分析

  • raw_input()等于将输入的内容记录为字符串。
  • input()是对raw_input()得到的字符串再使用eval()方法进行处理得到的结果,这个结果是符合python规则的值。

3.我这边遇到的问题

在进行下面的判断时

a = input()
if a == 'count':
    (...)

一定要输入带引号【”】的”count”才能判断成功,单单输入count会判断失败。
此时如果将input()变为raw_input()则只需要输入count就能成功判断。可能是eval函数的锅,暂时记录结果。

*参考其他博客:除非对 input() 有特别需要,否则一般情况下我们都是推荐使用 raw_input() 来与用户交互。

参考:

此时来看看eval()函数:

eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

eval是用来计算算式的,比如输入eval(“1+2”)可以得到3,其中提到的globals,locals是用来判断计算时使用的是哪里的变量的。暂时不展开。
http://www.coolpython.com/index.php?aid=12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值