日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python異常?ValueError的問題_python

作者:TCatTime ? 更新時間: 2022-12-05 編程語言

Python異常?ValueError

ValueError: invalid literal for int() with base 10: '*'

試圖將一個與數字無關的類型轉化為整數,會拋出該異常。

>>> int("99 years ago.")
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '99 years ago.'

規避方法:int函數參數應該合法使用。int函數使用傳送門:Python中的int函數使用

ValueError: too many values to unpack (expected 2)

試圖遍歷字典時同時遍歷鍵和值。

>>> demo = {"China": "Beijing", "Japan": "Tokyo"}
>>> for k, v in demo:
... ? ? print(k, v)
...
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

Python只允許對字典key的遍歷,因此上面的遍歷方式是錯誤的。

規避方法

方法一:使用dict[key]的方式同時獲取value

>>> demo = {"China": "Beijing", "Japan": "Tokyo"}
>>> for key in demo:
... ? ? print(key, demo[key])
...
China Beijing
Japan Tokyo

方法二:使用items方法

>>> demo = {"China": "Beijing", "Japan": "Tokyo", "the United States": "Washington D.C."}
>>> for key, value in demo.items():
... ? ? print(key, value)
...
China Beijing
Japan Tokyo
the United States Washington D.C.
ValueError: binary mode doesn't take an encoding argument

試圖以二進制模式讀取文件時指定編碼方式。

>>> with open("protoc-gen-go", "rb+", encoding="utf-8") as file:
... ? ? data = file.read()
...
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
ValueError: binary mode doesn't take an encoding argument

規避方法:避免使用encoding關鍵字

>>> with open("protoc-gen-go", "rb+") as file:
... ? ? data = file.read(10)
...
>>> data
b'\xcf\xfa\xed\xfe\x07\x00\x00\x01\x03\x00'

原文鏈接:https://blog.csdn.net/TCatTime/article/details/88085292

欄目分類
最近更新