Recent Posts

python compare logic operator


Hello I am Juny.

there are many operators in python.
we will learn logical operators and comparison operators of them.
they are no matter what the type of the operand is.

we will learn the other operators in proper subject.

at first,
I will explain why I said they are no matter what the type of the operand is.

there are mathematic operators.
they are limited to numeric data types.

but, logical and comparison operators have no limit of usage.

if we learn function overloading in the future, it is possible to use mathematic operators regardless of data types.

but, we will focus on the basics.

logical operator




operatoroperations
x or yif x is false, y. otherwise x.
x and yif x is false, x. otherwise y.
not xif x is false, true. otherwise false.


let's check it in code.


x = False
y = True
a = x or y
b = x and y
c = not x

print(a, b, c)





x is false and y is true. so, a is true.
x is false and y is true. so, b is false.
x is false. so, c is true.


comparison operators


as the literal, comparison operators compare two data.
there are 8 comparison operators in python.



operatoroperations
<less than
<=less or equal
>greater
>=greater or equal
==equal
!=not equal
isobject identity is equal
is notobject identity is not equal


the operators can be chained.
for example,
x < y <= z is possible.
that is same to x < y and y <= z.

but, first one evaluates y once.
second one evaluates y twice.

let's check them in code.


listA=list()
listB=list()

numberA=1
numberB=2

strA="A"
strB="B"

a1 = (listA < listB)
a2 = (listA > listB)
a3 = (listA == listB)
a4 = (listA is listB)

print(a1,a2,a3,a4)

b1 = (numberA < numberB)
b2 = (numberA > numberB)
b3 = (numberA == numberB)
b4 = (numberA is numberB)

print(b1,b2,b3,b4)

c1 = (strA < strB)
c2 = (strA > strB)
c3 = (strA == strB)
c4 = (strA is strB)

print(c1,c2,c3,c4)


list, string and number types are compared by comparison operators.


python compare operator



they have no meanings excepting for numeric data types.
but, they can be operated.

if you want to add meanings to them,
we have to overload the operators.
we will learn about that in the future.

all of the result of "is" operation is false.
the reason is that each data is located each memory.
on the other word, they have different memory location.

python attache unique identification to each memory location.
so, when "is" works, python compare their identifications.

"is" cannot be reimplemented.

lastly,
if the type of operands is different, TypeError raises.






python compare logic operator python compare logic operator Reviewed by Juny on 7월 20, 2019 Rating: 5

댓글 없음:

Powered by Blogger.