0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの数値型と数値演算子

Posted at

Pythonの数値型と数値演算子

Pythonでは、数値を扱う際に様々な数値型演算子を使用します。それぞれの型や演算子の使い方を理解することで、数値計算がより簡単になります。


1. 数値型(Numeric Types)

Pythonで使用できる主な数値型は以下の3種類です。

  1. 整数型 (int)

    • 小数点を持たない数値を扱います。
    • 例: 10, -5, 0
    print(type(10))  # <class 'int'>
    
  2. 浮動小数点型 (float)

    • 小数点を持つ数値を扱います。
    • 例: 3.14, -0.001, 0.0
    print(type(3.14))  # <class 'float'>
    
  3. 複素数型 (complex)

    • 実部と虚部を持つ数値を扱います。
    • 例: 3 + 5j, -2j
    print(type(1 + 2j))  # <class 'complex'>
    

2. 数値演算子(Operators)

Pythonでは、数値に対して様々な演算を行うことができます。以下は主な演算子のリストです。

1. 四則演算

  • + : 加算
  • - : 減算
  • * : 乗算
  • / : 除算(結果は常に float 型)
a = 10
b = 5
print(a + b)  # 15
print(a - b)  # 5
print(a * b)  # 50
print(a / b)  # 2.0

2. 剰余(Modulus)

  • % : 割り算の余りを返します。
print(14 % 3)  # 2

3. 切り捨て除算(Floor Division)

  • // : 小数点以下を切り捨てた整数部分を返します。
print(14 // 3)  # 4

4. べき乗(Exponentiation)

  • ** : 指定した数をべき乗します。
print(2 ** 3)  # 8

3. 特徴的な計算のルール

  1. 整数 (int) と浮動小数点 (float) の計算

    • int 型と float 型の計算結果は常に float 型になります。
    • 例: 10 + 0.510.5float 型)
    a = 5
    b = 2.0
    print(a + b)  # 7.0
    
  2. 優先順位

    • 演算子には計算の優先順位があります。
      • 例: *(乗算)や /(除算)は +(加算)や -(減算)よりも優先されます。
    • 必要に応じて括弧 () を使うと、計算順序を明示できます。
    print(5 + 2 * 3)  # 11
    print((5 + 2) * 3)  # 21
    
  3. 負の数の切り捨て除算

    • 負の数の場合、切り捨ては「小さい方向」に丸めます。
      • 例: -7 // 3-3

4. 複合代入演算子(Augmented Assignment)

複合代入演算子を使うことで、計算と代入を同時に行えます。

主な複合代入演算子

  1. += : 加算して代入
  2. -= : 減算して代入
  3. *= : 乗算して代入
  4. /= : 除算して代入(float 型を返す)
  5. //= : 切り捨て除算して代入
  6. %= : 剰余を計算して代入
  7. **= : べき乗を計算して代入

x = 10
x += 5  # x = x + 5
print(x)  # 15

x *= 2  # x = x * 2
print(x)  # 30

5. 応用例: 偶数・奇数判定

剰余演算子 % を使って、数値が偶数か奇数かを判定できます。

number = 10
if number % 2 == 0:
    print("偶数です")
else:
    print("奇数です")
出力
偶数です

6. まとめ

  • Pythonでは、数値型は主に intfloatcomplex の3種類があります。
  • 数値演算子を使うと、加算、減算、乗算、除算などの計算が簡単に行えます。
  • 優先順位や型変換のルールを理解しておくと、複雑な計算を正確に扱えます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?