【问题标题】:Evaluation of 'not (False and True)'评估“不(假和真)”
【发布时间】:2015-05-30 20:04:21
【问题描述】:

我遇到了这个例子 ("Hacking Secret Ciphers with Python", p135) 我很困惑:

not (False and True)

该示例表明它的计算结果为False,但我不明白为什么。如果括号修改了优先级,那么我们肯定正在评估:

not (False)

计算结果为True,不是吗?还是我错过了什么?

// output functions are configurable.  This one just appends some text
// to a pre element.
function outf(text) {
  var mypre = document.getElementById("output");
  mypre.innerHTML = mypre.innerHTML + text;
}

function builtinRead(x) {
  if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
    throw "File not found: '" + x + "'";
  return Sk.builtinFiles["files"][x];
}

// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
  var prog = document.getElementById("yourcode").value;
  var mypre = document.getElementById("output");
  mypre.innerHTML = '';
  Sk.pre = "output";
  Sk.configure({
    output: outf,
    read: builtinRead
  });
  (Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
  var myPromise = Sk.misceval.asyncToPromise(function() {
    return Sk.importMainWithBody("<stdin>", false, prog, true);
  });
  myPromise.then(function(mod) {
      console.log('success');
    },
    function(err) {
      console.log(err.toString());
    });
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>

<h3>Try This</h3> 
<form>
  <textarea id="yourcode" cols="40" rows="10">print(not (False and True))
  </textarea>
  <br />
  <button type="button" onclick="runit()">Run</button>
</form>
<pre id="output"></pre> 
<!-- If you want turtle graphics include a canvas -->
<div id="mycanvas"></div>

【问题讨论】:

  • 你有没有实际尝试过这个not (False and True) 计算结果为 True
  • 我无法尝试,因为我只有书和手机!我想我可以放心地假设这只是书中的一个错字!
  • 请注意,网上有各种 REPL,所以如果你可以在 SO 上发帖,你可以运行一些代码!
  • 你是对的,从没想过要尝试一下 :)
  • 在引用的书中发生此错误的操作是正确的。很明显,抄本不是真的。我最好的猜测是这本书打算使用or,而不是andnot False or True 是True,但not (False or True) 是False。

标签: python python-3.x boolean


【解决方案1】:

这其实是在the errata:

第 135 页,交互式 shell 应如下所示:

>>> not False and False # not False evaluates first 
True 
>>> not (False and False) # (False and False) evaluates first 
False 

(感谢 Omer Chohan)

它已在the online version of the chapter 中得到更正,尽管 PDF 中没有。

【讨论】:

    【解决方案2】:

    not (False and True) 绝对是True,如果你在 Python REPL 中键入表达式,就可以看到。谁声称它是False

    【讨论】:

    • 不幸的是,我无法尝试在计算机附近输入它,我正在阅读 invent with python 中的“Hacking Secret Ciphers with Python”。第 9 章。
    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多