“带有基数10的int()的无效文字:"这究竟意味着什么? [英] "invalid literal for int() with base 10:" What does this actually mean?
问题描述
初学者在这里!我正在编写一个简单的代码来计算项目在列表中显示的次数(例如 count([1,3,1,4,1,5],1)
将返回3)。
Beginner here! I am writing a simple code to count how many times an item shows up in a list (ex. count([1, 3, 1, 4, 1, 5], 1)
would return 3).
这是我原来的:
def count(sequence, item):
s = 0
for i in sequence:
if int(i) == int(item):
s += 1
return s
每次我提交此代码时,我都会
Every time I submitted this code, I got
基数为10的int()的文字无效:
"invalid literal for int() with base 10:"
我已经发现了正确的代码是:
I've since figured out that the correct code is:
def count(sequence, item):
s = 0
for i in sequence:
if **i == item**:
s += 1
return s
但是,我只是对这个错误陈述的含义感到好奇。为什么我不能留在 int()
?
However, I'm just curious as to what that error statement means. Why can't I just leave in int()
?
推荐答案
错误是基于10的int()的无效文字:。这只是意味着您传递给 int
的参数看起来不像数字。换句话说,它是空的,或者除了数字之外还有一个字符。
The error is "invalid literal for int() with base 10:". This just means that the argument that you passed to int
doesn't look like a number. In other words it's either empty, or has a character in it other than a digit.
这可以在python shell中重现。
This can be reproduced in a python shell.
>>> int("x")
ValueError: invalid literal for int() with base 10: 'x'
这篇关于“带有基数10的int()的无效文字:"这究竟意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!