>  기사  >  백엔드 개발  >  파이썬 연산자

파이썬 연산자

高洛峰
高洛峰원래의
2016-11-23 11:19:491206검색

연산자란 무엇인가요?

이 장에서는 주로 Python의 연산자를 설명합니다. 간단한 예를 들어보겠습니다: 4 +5 = 9. 예제에서는 4와 5를 피연산자라고 하며 "+" 기호는 연산자입니다.

Python 언어는 다음 유형의 연산자를 지원합니다.

산술 연산자

비교(관계형) 연산자

대입 연산자

논리 연산자

비트 연산자

멤버 연산자

식별 연산자

연산자 우선순위

다음으로 파이썬의 연산자를 하나씩 배워보겠습니다.

Python 산술 연산자

다음은 변수 a가 10이고 변수 b가 20이라고 가정합니다.

연산자

설명

+ 더하기 - 두 개체를 더하기 a + b 출력 결과 30

- 빼기 - 음수 또는 한 숫자에서 다른 숫자를 빼기 A 숫자 a - b 출력 결과 - 10

* 곱하기 - 두 숫자를 곱하거나 여러 번 반복되는 문자열을 반환합니다. a * b 출력 결과 200

/ 나누기 - x y로 나누기 b / a 출력 결과 2

% Modulo - 나눗셈의 나머지를 반환합니다. b % a 출력 결과 0

** 거듭제곱 - x의 y 거듭제곱을 반환합니다. a**b 출력 결과 20

// 나누기 - 몫의 정수 부분 반환 9//2 출력 결과 4, 9.0//2.0 출력 결과 4.0

다음 예에서는 Python의 모든 산술 연산자의 연산을 보여줍니다.

#!/usr/bin/python
 
a = 21
b = 10
c = 0
 
c = a + b
print "Line 1 - Value of c is ", c
 
c = a - b
print "Line 2 - Value of c is ", c
 
c = a * b
print "Line 3 - Value of c is ", c
 
c = a / b
print "Line 4 - Value of c is ", c
 
c = a % b
print "Line 5 - Value of c is ", c
 
a = 2
b = 3
c = a**b
print "Line 6 - Value of c is ", c
 
a = 10
b = 5
c = a//b
print "Line 7 - Value of c is ", c

위 예의 출력 결과:

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

파이썬 비교 연산자

다음은 변수 a가 10이고 변수 b가 20이라고 가정합니다.

연산자

설명

Instance

== Equal - 객체가 동일한지 비교합니다. (a == b) False를 반환합니다.

!= 같지 않음 - 두 개체가 같지 않은지 비교합니다(a != b).

a8093152e673feb7aba1828c43532094 같지 않음 - 두 개체가 같지 않은지 비교합니다(a ddd849e357a85aa5a0680a8d66a9b3ef b) 참을 반환합니다. 이 연산자는 != 와 유사합니다.

> 보다 큼 - x가 y보다 큰지 여부를 반환합니다(a > b). False를 반환합니다.

483c96ec3a33095842026dc81933baed= 크거나 같음 - x가 y보다 크거나 같은지 여부를 반환합니다. (a >= b)는 False를 반환합니다.

393159b744f90749fb94757297f1cea3>    右移动运算符    a >> 2 输出结果 15 ,二进制解释: 0000 1111    

以下实例演示了Python所有位运算符的操作:

#!/usr/bin/python
 
a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
c = 0
 
c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c
 
c = a | b;        # 61 = 0011 1101
print "Line 2 - Value of c is ", c
 
c = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", c
 
c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c
 
c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c
 
c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c

   

以上实例输出结果:

Line 1 - Value of c is 12

Line 2 - Value of c is 61

Line 3 - Value of c is 49

Line 4 - Value of c is -61

Line 5 - Value of c is 240

Line 6 - Value of c is 15

   

Python逻辑运算符

Python语言支持逻辑运算符,以下假设变量a为10,变量b为20:

运算符

描述

实例

and    布尔"与" - 如果x为False,x and y返回False,否则它返回y的计算值。    (a and b) 返回 true。    

or    布尔"或" - 如果x是True,它返回True,否则它返回y的计算值。    (a or b) 返回 true。    

not    布尔"非" - 如果x为True,返回False。如果x为False,它返回True。    not(a and b) 返回 false。    

以下实例演示了Python所有逻辑运算符的操作:

#!/usr/bin/python
 
a = 10
b = 20
c = 0
 
if ( a and b ):
   print "Line 1 - a and b are true"
else:
   print "Line 1 - Either a is not true or b is not true"
 
if ( a or b ):
   print "Line 2 - Either a is true or b is true or both are true"
else:
   print "Line 2 - Neither a is true nor b is true"
 
 
a = 0
if ( a and b ):
   print "Line 3 - a and b are true"
else:
   print "Line 3 - Either a is not true or b is not true"
 
if ( a or b ):
   print "Line 4 - Either a is true or b is true or both are true"
else:
   print "Line 4 - Neither a is true nor b is true"
 
if not( a and b ):
   print "Line 5 - a and b are true"
else:
   print "Line 5 - Either a is not true or b is not true"
   
以上实例输出结果:
Line 1 - a and b are true
Line 2 - Either a is true or b is true or both are true
Line 3 - Either a is not true or b is not true
Line 4 - Either a is true or b is true or both are true
Line 5 - a and b are true

   

Python成员运算符

除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。

运算符

描述

实例

in    如果在指定的序列中找到值返回True,否则返回False。    x 在 y序列中 , 如果x在y序列中返回True。    

not in    如果在指定的序列中没有找到值返回True,否则返回False。    x 不在 y序列中 , 如果x不在y序列中返回True。    

以下实例演示了Python所有成员运算符的操作:

#!/usr/bin/python
 
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
 
if ( a in list ):
   print "Line 1 - a is available in the given list"
else:
   print "Line 1 - a is not available in the given list"
 
if ( b not in list ):
   print "Line 2 - b is not available in the given list"
else:
   print "Line 2 - b is available in the given list"
 
a = 2
if ( a in list ):
   print "Line 3 - a is available in the given list"
else:
   print "Line 3 - a is not available in the given list"

   

以上实例输出结果:

Line 1 - a is not available in the given list

Line 2 - b is not available in the given list

Line 3 - a is available in the given list

   

Python身份运算符

身份运算符用于比较两个对象的存储单元

运算符

描述

实例

is    is是判断两个标识符是不是引用自一个对象    x is y, 如果 id(x) 等于 id(y) , is 返回结果 1    

is not    is not是判断两个标识符是不是引用自不同对象    x is not y, 如果 id(x) 不等于 id(y). is not返回结果 1    

以下实例演示了Python所有身份运算符的操作:

#!/usr/bin/python
 
a = 20
b = 20
 
if ( a is b ):
   print "Line 1 - a and b have same identity"
else:
   print "Line 1 - a and b do not have same identity"
 
if ( id(a) == id(b) ):
   print "Line 2 - a and b have same identity"
else:
   print "Line 2 - a and b do not have same identity"
 
b = 30
if ( a is b ):
   print "Line 3 - a and b have same identity"
else:
   print "Line 3 - a and b do not have same identity"
 
if ( a is not b ):
   print "Line 4 - a and b do not have same identity"
else:
   print "Line 4 - a and b have same identity"

   

以上实例输出结果:

Line 1 - a and b have same identity

Line 2 - a and b have same identity

Line 3 - a and b do not have same identity

Line 4 - a and b do not have same identity

   

Python运算符优先级

以下表格列出了从最高到最低优先级的所有运算符:

运算符

描述

**    指数 (最高优先级)    

~ + -    按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)    

* / % //    乘,除,取模和取整除    

+ -    加法减法    

>> 576f6c06acde14831fa5e2d2bcea0818 >=    比较运算符    

a8093152e673feb7aba1828c43532094 == !=    等于运算符    

= %= /= //= -= += *= **=    赋值运算符    

is is not    身份运算符    

in not in    成员运算符    

not or and    逻辑运算符    

以下实例演示了Python所有运算符优先级的操作:

#!/usr/bin/python
 
a = 20
b = 10
c = 15
d = 5
e = 0
 
e = (a + b) * c / d       #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ",  e
 
e = ((a + b) * c) / d     # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ",  e
 
e = (a + b) * (c / d);    # (30) * (15/5)
print "Value of (a + b) * (c / d) is ",  e
 
e = a + (b * c) / d;      #  20 + (150/5)
print "Value of a + (b * c) / d is ",  e

   

以上实例输出结果:

Value of (a + b) * c / d is 90

Value of ((a + b) * c) / d is 90

Value of (a + b) * (c / d) is 90

a+(b*c)/d의 값은 50입니다.


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Python 조건문다음 기사:Python 조건문