Python逻辑运算符用法示例指南

本文概述

运算符用于对值和变量执行运算。这些是执行算术和逻辑计算的特殊符号。操作员操作的值称为操作数.

目录逻辑运算符逻辑与运算符逻辑或运算符逻辑非运算符逻辑运算符的评估顺序

逻辑运算符

在Python中, 逻辑运算符用于条件语句(True或False)。他们表演逻辑与, 逻辑或和逻辑非操作。

操作符描述语法
and逻辑AND:如果两个操作数都为true, 则为truex和y
or逻辑或:如果任何一个操作数为true, 则为truex或y
not逻辑非:如果操作数为假, 则为真不是x

逻辑AND运算子

逻辑运算符返回true如果两个操作数均为True, 则返回false.

Python逻辑和运算符2

示例1:

# Python program to demonstrate

# logical and operator

a = 10

b = 10

c = - 10

if a> 0 and b> 0 :

print ( "The numbers are greater than 0" )

if a> 0 and b> 0 and c> 0 :

print ( "The numbers are greater than 0" )

else :

print ( "Atleast one number is not greater than 0" )

输出如下:

The numbers are greater than 0

Atleast one number is not greater than 0

示例2:

# Python program to demonstrate

# logical and operator

a = 10

b = 12

c = 0

if a and b and c:

print ( "All the numbers have boolean value as True" )

else :

print ( "Atleast one number has boolean value as False" )

输出如下:

Atleast one number has boolean value as False

注意:如果在使用and运算符时第一个表达式评估为假, 则不评估其他表达式。

逻辑或运算符

如果两个操作数中的任何一个为True, 则逻辑或运算符将返回True。

Python逻辑或运算符

示例1:

# Python program to demonstrate

# logical or operator

a = 10

b = - 10

c = 0

if a> 0 or b> 0 :

print ( "Either of the number is greater than 0" )

else :

print ( "No number is greater than 0" )

if b> 0 or c> 0 :

print ( "Either of the number is greater than 0" )

else :

print ( "No number is greater than 0" )

输出如下:

Either of the number is greater than 0

No number is greater than 0

示例2:

# Python program to demonstrate

# logical and operator

a = 10

b = 12

c = 0

if a or b or c:

print ( "Atleast one number has boolean value as True" )

else :

print ( "All the numbers have boolean value as False" )

输出如下:

Atleast one number has boolean value as True

注意:如果在使用或运算符时第一个表达式评估为True, 则不会评估其他表达式。

逻辑非运算符

逻辑非运算符使用单个布尔值。如果布尔值是true它返回false反之亦然。

Python逻辑非运算符

例子:

# Python program to demonstrate

# logical not operator

a = 10

if not a:

print ( "Boolean value of a is True" )

if not (a % 3 = = 0 or a % 5 = = 0 ):

print ( "10 is not divisible by either 3 or 5" )

else :

print ( "10 is divisible by either 3 or 5" )

输出如下:

10 is divisible by either 3 or 5

逻辑运算符的评估顺序

对于多个运算符, Python始终从左到右评估表达式。可以通过以下示例进行验证。

例子:

# Python program to demonstrate

# order of evaluation of logical

# operators

def order(x):

print ( "Method called for value:" , x)

return True if x> 0 else False

a = order

b = order

c = order

if a( - 1 ) or b( 5 ) or c( 10 ):

print ( "Atleast one of the number is positive" )

输出如下:

Method called for value: -1

Method called for value: 5

Atleast one of the number is positive

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

以上是 Python逻辑运算符用法示例指南 的全部内容, 来源链接: utcz.com/p/204383.html

回到顶部