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