python的三目运算符和not in运算符使用示例

yipeiwu_com6年前Python基础

三目运算符也就是三元运算符

一些语言(如Java)的三元表达式形如:

判定条件?为真时的结果:为假时的结果

result=x if x

Python的三元表达式有如下几种书写方法:

if __name__ == '__main__':
	a = ''
	b = 'True'
	c = 'False'
	
	#方法一:为真时的结果 if 判定条件 else 为假时的结果
	d = b if a else c
	print('方法一输出结果:' + d)
	
	#方法二:判定条件 and 为真时的结果 or 为假时的结果
	d = a and b or c
	print('方法二输出结果:' + d)
	
	#以上两种方法方法等同于if ... else ...
	if a:
		d = b
	else:
		d = c
	print('if语句的输出结果:' + d)

输出结果:

说明:
判断条件:a为空串,所以判断条件为假
当判断条件为真时的结果:d = b
当判断条件为假时的结果:d = c

x = [x for x in range(1,10)]
print(x)
y =[]

result = True if 12 not in x else False # this is the best way
print(result)
result = True if not 12 in x else False # this way just like as " (not 12) in x"
print(result)

print(x is y)
print(x is not y) # this is the best way
print(not x is y) # this way just like as " (not x ) is y" ,so upper is the best way

result = 2 if 1 < 2 else 5 if 4 > 5 else 6 # just as 1 > 2 ? 2 : 4 > 5 ? 5 : 6
print(result)

python中的not具体使用及意思

name=''
while not name:
 name=raw_input(u'请输入姓名:')
print name

python中的not具体表示是什么:

在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法:
(1) not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句。比如:

a = False
if not a: (这里因为a是False,所以not a就是True)
 print "hello"


这里就能够输出结果hello
(2) 判断元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,这句话的意思是如果a不在列表b中,那么就执行冒号后面的语句,比如:

a = 5
b = [1, 2, 3]
if a not in b:
 print "hello"

这里也能够输出结果hello

not x     意思相当于     if x is false, then True, else False

代码中经常会有变量是否为None的判断,有三种主要的写法:

第一种是`if x is None`;
第二种是 `if not x:`;
第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) 。

如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]   # You don't want to fall in this one.
>>> not x
False

更多内容可以参考这篇文章:/post/93165.htm

相关文章

一个超级简单的python web程序

在MAC/LINUX环境下,执行vi hello.py命令,并输入以下代码 import web import sys urls = ("/Service/hello","hel...

Django重置migrations文件的方法步骤

Django开发过程中如果数据库变动过多导致migrations的文件越来越多,管理起来很不方便, 幸运的是Django提供了一种方式可以是这些文件重置到0001状态,而且不删除原有数据...

跟老齐学Python之编写类之二方法

跟老齐学Python之编写类之二方法

数据流转过程 除了在类中可以写这种函数之外,在类中还可以写别的函数,延续上一讲的例子: 复制代码 代码如下: #!/usr/bin/env python #coding:utf-8 cl...

python format 格式化输出方法

0、前言 在python2.7及以上的版本,str.format()的方式为格式化提供了非常大的便利。与之前的%型格式化字符串相比,他显得更为方便与优越。下面我们就来看看format的具...

Python 实现try重新执行

Python try重新执行: def numberinput(): #创建方法 try: s=int(input('number:')) return s...