python - 第8行: ValueError: invalid literal for int() with base 10: ' '

标签 python error-handling

我是一个初学者程序员。我想编写一个程序,为我提供输入数字中所有4位相邻数字产品的最大乘积。
因此,如果输入为“12345678”
可能的选择是1234、2345、3456、4567、5678,最大乘积是5 * 6 * 7 * 8。

我的代码:

number = str(input("Enter a number:"))
i = 0
L = []
while (i!=len(number)-3):
    a = int(number[i])
    b = int(number[i+1])
    c = int(number[i+2])
    d = int(number[i+3])
    product = a*b*c*d
    L.append(product)
    i = i+1
print(L)
print(number)
print(max(L))

我需要将此数字应用于1000位数字。我的代码适用于8位输入数字,并给出了500位数字的答案。

但是我尝试用一​​个600位数的数字进行尝试,并抛出了此错误。

我知道ValueError是一个错误,当给函数调用的参数具有正确的类型但值不正确时,会出现此错误。还有一些示例,说明用户何时在代码Eg中输入字符串“Alexander”作为输入:int(input(“Enter a number”))

错误是由于''无法转换为整数的空字符串。但是我不明白在哪里/为什么形成空字符串。

我已经阅读了有关此错误类型的其他一些答案,但都涉及使用我不熟悉并因此无法理解的Python功能的代码。我只是一个初学者!所以,请帮忙!

对于违反有关问题形成的任何规则表示歉意!

最佳答案

您在那里有一个空格,而不是一个空字符串。最有可能的是,您只需在输入末尾敲空格键,Python无法将其转换为整数。您可以只是确保在结尾处不留空格,也可以对输入进行一些检查(例如,添加一行number = number.strip()以删除任何尾随空格)。

关于python - 第8行: ValueError: invalid literal for int() with base 10: ' ' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33479946/

相关文章:

github - 将 FormSpree 集成到 GitHub Jekyll 中(返回消息 : Form should post)

Powershell 错误 : Is there a way to trap "command not found" errors into a custom function?

python - 在Python Flask中如何允许用户重新排列列表项并记录在数据库中

python - Openpyxl - 我可以使用 Openpyxl 创建水平条形图吗?

python - 关于加载 npy 文件并调查其中的内容

c++ - 我如何在 C++ 中使用 errno

Python释放字典的内存

python - Tornado "error: [Errno 24] Too many open files"错误

sql-server - 替换 SQL Server 中的单引号

r - 错误: Data source must be a dictionary (dplyr)