亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python異常?ValueError的問題

 更新時間:2022年11月03日 09:52:22   作者:TCatTime  
這篇文章主要介紹了Python異常?ValueError的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Python異常 ValueError

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

試圖將一個與數(shù)字無關(guān)的類型轉(zhuǎn)化為整數(shù),會拋出該異常。

>>> 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.'

規(guī)避方法:int函數(shù)參數(shù)應(yīng)該合法使用。int函數(shù)使用傳送門:Python中的int函數(shù)使用

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的遍歷,因此上面的遍歷方式是錯誤的。

規(guī)避方法

方法一:使用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

試圖以二進(jìn)制模式讀取文件時指定編碼方式。

>>> 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

規(guī)避方法:避免使用encoding關(guān)鍵字

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

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論