LoginSignup
0
0

Pythonの割り算でエラーメッセージの出方が微妙に違う

Last updated at Posted at 2023-05-29

本記事の背景

あるサイトの挑戦問題において、0割エラーにおいて出力されるエラーメッセージに微妙な違いがある為、本メモを残す

Pythonの割り算

まずは正解のソースコードを以下に示す

n = int(input())

for n1 in range(0,n):
    a,b = map(str, input().split())
    try:
        print(int(a)//int(b))
    except (ZeroDivisionError, ValueError) as e:
        print("Error Code:", e)

入力値

3
3 0
3 $
3 1

出力結果

Error Code: integer division or modulo by zero
Error Code: invalid literal for int() with base 10: '$'
3

引っかかったポイント

try:
    print(int(a)/int(b))
except (ZeroDivisionError, ValueError) as e:
    print("Error Code:", e)

上記のソースコードだとエラーメッセージが以下になる

Error Code: integer division by zero
Error Code: invalid literal for int() with base 10: '$'
3

「integer division or modulo by zero」と「integer division by zero」という微妙に違っていた。
実は、Pythonで割り算をする場合
a/b → 「商+余り」を含めて小数で出力する
a//b → 「商」のみ出力する
以上を押さえておくと良いかと思います。

0
0
1

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