is 语法带来的误读

栏目: Python · 发布时间: 7年前

内容简介:Python 的成功一个原因是它的可读性,代码清晰易懂,更容易被人类所理解,但有时可读性会产生误解。假如要判断一个变量是不是 17,那可以:

起步

Python 的成功一个原因是它的可读性,代码清晰易懂,更容易被人类所理解,但有时可读性会产生误解。

假如要判断一个变量是不是 17,那可以:

if x is 17:

x 是 17 肯定是比 x == 17 更加口语化的。

is的误解

但是如果你尝试:

if name is "weapon":

这个判断不见得管用。 is 用来检查左侧和右侧是否是完全相同的对象。如果有两个不同的字符串对象,每个对象的值是相同的,应该使用 == 来判断,因为 is 的用法与口语上的区别挺大的:

if 999 + 1 is 1000:  # False

正因为这样的误解,在 if 判断条件上容易让初学者掉坑:

answer = 'yes'
if answer is 'y' or 'yes':

你会发现不管变量是什么值,判断都是为真。因为 is 的优先级高,相当于 if (answer is 'y') or ('yes')

正确的方法应该是 if answer == 'y' or answer == 'yes' 或者 if answer in ('y', 'yes')

is not 上的混淆

>>> 'something' is not None
True
>>> 'something' is (not None)
False

is not 是一个二元运算符,应该视为一个整体,不要因为中间空格而当成两个词。底层上,它们也是一个操作符,CPython 将 s is not None 翻译成的字节码为:

6 LOAD_NAME                0 (s)
 8 LOAD_CONST               1 (None)
10 COMPARE_OP               9 (is not)

is not 是对 is 相对应的操作符。也可以视为是将 is 判断的结果再进行取反。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Guide to Monte Carlo Simulations in Statistical Physics

A Guide to Monte Carlo Simulations in Statistical Physics

Landau, David P./ Binder, Kurt / Cambridge Univ Pr / 2005-9 / 786.00元

This new and updated edition deals with all aspects of Monte Carlo simulation of complex physical systems encountered in condensed-matter physics, statistical mechanics, and related fields. After brie......一起来看看 《A Guide to Monte Carlo Simulations in Statistical Physics》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器