[Python] Arithmetic in Python and Augmented Assignment

2023. 6. 12. 17:50·Programming
728x90
728x90

이 문서는 Python의 Arithmetic Operations 와 Augmented Assignment를 다룸.

 

Python에서 Operator(연산자)는 Variable(변수)나 Value에 대해 Operation을 수행하는 기호 또는 키워드임.

이중에서도 Arithmetic Operators는 Numeric Data 에 대해 덧셈, 곱셈, 뺄셈, 나눗셈 등의 수학적 계산을 수행하는 Operators를 가리킴.

 

Operation에 대한 개념은 다음을 참고: https://dsaint31.me/mkdocs_site/CE/ch01/ch01_00_data_representation/?h=operator#4-operations

 

BME

data information instruction operation Representation of data within a computer system. 1. Data vs. Information Data 어떤 처리가 이루어지지 않은 상태의 character(문자)나 number(수치), image(그림) 등으로 단순히 측정하고 수

dsaint31.me


1. Precedence of Arithmetic Operations

Higher     ** > -(negation) > * = / = // = % > + = -(subtraction)     Lower

  • Precedence(우선순위)를 기억하는 것도 중요하지만,
  • 헷갈리면 그냥 parentheses로 묶어주면 된다. (가독성을 위해서도 이를 추천)
  • 동시에 3+2와 같은 간단한 expression은 굳이 parentheses로 묶지 말 것. (이 경우, 복잡한 expression등과 헷갈리게 됨)
더보기
https://python.plainenglish.io/a-comprehensive-guide-to-operators-in-python-understanding-the-building-blocks-of-expressions-be90ac565151

그 외 연산자들:

https://ds31x.tistory.com/54

 

[Python] Boolean Operators, Relational Operators, and Membership Operator

위 그림에서 arithmetic operators는 제외됨.https://dsaint31.tistory.com/516 -(negation) > * = / = // = % > + = -(subtraction) Lower우선순위를 기억하는 것도 중요하지만, 헷갈리면 그냥 parentheses로 묶어주면 된다. (가독

ds31x.tistory.com


 


2. Unary Operator (단항 연산자)

2-0. Negation

음수를 표현. (subtraction이 아닌)

>>> -2
-2
>>> --2
2
>>> ---2
-2
>>> ---2.
-2.0

3. Binary Operator (이항 연산자)

3-0. exponentiation : **

2의 3 제곱은 다음 2**3 으로 표시함.


3-1. 사칙연산 : +, -, *, /

우리가 아는 사칙연산 그대로임.

  • addition
  • subtraction
  • multiplication
  • division

단, multiplication이 *(asterisk)라는 것과 division /이 항상 float type으로 결괏값을 내놓는다는 점만 기억할 것.

>>> 2+3
5
>>> 2-3
-1
>>> 2*3
6
>>> 2/3  
0.6666666666666666
>>> 4/2
2.0
>>> 2.+3  # float
5.0

3-2. Integer Division (or floor division) : //

python에서 //는 나누기 결과를 항상 int type이 될 수 있는 값으로 반환해준다.

  • 이렇게 설명한 이유는 result가 1.0과 같이 float type이 될 수도 있기 때문임)
  • "//의 결과"와 "나누어진 수"를 곱하면 항상 //의 왼쪽의 수보다 작게 나옴.
  • 정확한 값을 구한 후 내림(floor)를 처리하면 됨.
>>> 12//10
1
>>> 19//10
1
>>> -12//10 # floor(-1.2) = -2 ,작은 정수값이 답임.
-2
>>> -9//10
-1
>>> -19//10 # floor(-1.9) 이며 이는 -2가 됨.
-2
>>> 12.//10 # 하나라도 float면 결과도 float: floor(1.2)= 1.0
1.0
>>> 12//10.
1.0

3-3. modulo (or remainder) : %

나머지 연산이라고도 불림.

 

modulo 라는 용어로 자주 불리지만,
엄밀하게는 remainder operator 임.

주의할 것은

  • 결괏값의 sign이 항상 나누어주는 수(divisor)의 sign이 을 따름 (0은 sign이 없는 점도 기억할 것.)
  • 이는 수학적 modulo와 조금 차이가 있으며 % 연산자는 다음으로 구해짐.

$$a \% b = a - ( a // b) * b$$

  • 참고로, 수학적 modulo에선 b가 항상 양수임.
>>> 20%3
2
>>> 20%2
0
>>> 20%-2
0
>>> -20%2
0
>>> 20%-3 # 20-(20//-3)*-3 = 20-(-7)*-3 = -1
-1
>>> -20%3 # -20-(-20//3)*3 = -20-(-7)*3 = 1
1
>>> -20.%2  # float
0.0
>>> 20%3.
2.0

4. Augmented Assignment

Assignment와 arithmetic operation이 결합한 것.

Augmented Assignment
Symbol
예제 결과
+= x = 3
x += 5
x는 8이 됨.
(정확히는 x는 8을 참조하게 됨)
-= x = 3
x -= 5
x는 -2가 됨.
(정확히는 x는 -2를 참조하게 됨)
*= x = 3
x *= 5
x는 15가 됨.
(정확히는 x는 15를 참조하게 됨)
/= x = 7
x /= 2
x는 3.5가 됨.
(정확히는 x는 3.5를 참조하게 됨)
//= x = 7
x //= 2
x는 3이 됨
(정확히는 x는 3을 참조하게 됨)
%= x = 7
x %= 2
x는 1이 됨
(정확히는 x는 1을 참조하게 됨)
**= x = 7
x **= 2
x는 49가 됨
(정확히는 x는 49를 참조하게 됨)

 

할당에 대한 참고 자료 : 2023.06.20 - [Programming] - [Python] Assignment (Basic)

 

[Python] Assignment (Basic)

1. General form Assignment statement의 일반적인 형태는 다음과 같음. varible = expression 2. 수행 순서 = 기호의 오른쪽의 expression을 evaluation함 (값으로 reduction) 1번의 값에 해당하는 object가 저장된 memory address

dsaint31.tistory.com


읽어보면 좋은 자료

operation에 대한 설명 : https://dsaint31.me/mkdocs_site/CE/ch01/ch01_00_data_representation/#operations

 

BME228

Representation of data within a computer system. Data vs. Information Data 어떤 처리가 이루어지지 않은 상태의 character(문자)나 number(수치), image(그림) 등으로 단순히 측정하고 수집된 것 을 의미함. 어떤 의미나

dsaint31.me

https://ds31x.tistory.com/54

 

[Python] Boolean Operators, Relational Operators, and Membership Operator

위 그림에서 arithmetic operators는 제외됨.https://dsaint31.tistory.com/516 -(negation) > * = / = // = % > + = -(subtraction) Lower우선순위를 기억하는 것도 중요하지만, 헷갈리면 그냥 parentheses로 묶어주면 된다. (가독

ds31x.tistory.com


https://ds31x.tistory.com/194

 

[Python] Arithmetic, Variables, Types and Assignment

Numeric Type and Arithmetic in Python (+Augmented Assignment)https://dsaint31.tistory.com/516 -(negation) > * = / = // = % > + = -(subtraction) Lower우선순위를 기억하는 것도 중요하지만, 헷갈리면 그냥 parentheses로 묶어주면 된다

ds31x.tistory.com

 


 

728x90

'Programming' 카테고리의 다른 글

[Python] Strong Typing이란? with Object  (1) 2023.06.13
[Python] Variable (and Object)  (0) 2023.06.13
[Python] (Data) Type: Summary  (0) 2023.06.12
[Python] Expression vs. Statement  (0) 2023.06.12
[WSL] Install WSL (Windows Subsystem for Linux)  (0) 2023.06.12
'Programming' 카테고리의 다른 글
  • [Python] Strong Typing이란? with Object
  • [Python] Variable (and Object)
  • [Python] (Data) Type: Summary
  • [Python] Expression vs. Statement
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (785)
      • Private Life (15)
      • Programming (55)
        • DIP (116)
        • ML (34)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (368)
        • Signals and Systems (115)
        • Math (176)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (61)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (7)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    signals_and_systems
    Probability
    Programming
    fourier transform
    opencv
    ML
    Python
    math
    Term
    SS
    Optimization
    numpy
    Vector
    linear algebra
    인허가제도
    function
    random
    signal_and_system
    cv2
    SIGNAL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] Arithmetic in Python and Augmented Assignment
상단으로

티스토리툴바