gpt4 book ai didi

python - 值错误 : invalid literal for int() with base 10 for non-digits

转载 作者:行者123 更新时间:2023-11-28 20:09:59 26 4
gpt4 key购买 nike

我正在尝试创建一个简单的程序来读取 4 位数字的字符串,确保它确实是 4 位数字,确保没有非数字,然后将前两位数字与后两位数字分开并将它们加在一起.我可以使一切正常,但我仍然遇到此错误:

ValueError:以 10 为底的 int() 无效文字:

只有当我尝试使用诸如“456f”之类的字符串时才会发生这种情况。

我可以做些什么来解决这个问题?

代码:

    s = input('please type a 4-digit integer \n')
valid = True
for c in s:
if len(s)!= 4:
valid = False
if not c.isdigit():
print (c, 'is not a valid input')
number = int(s)
firstOne = number // 100
secondOne = number % 100
sum = firstOne + secondOne
x = '/'
if valid == True:
print('your integer is ' + str(number), x, 'first two digits are ' + str(firstOne), x, 'second two digits are ' + str(secondOne), x, 'sum of two new numbers is ' + str(sum))
else:
print(len(s), 'is an invalid amount of digits')

最佳答案

您正在检查是否所有字符都是数字,但此检查没有任何后果——即使您发现了无效字符,您也只是继续进行。这会使代码失败并显示引用的错误消息。

我建议使用专用函数来读取重复查询直到获得有效输入的整数:

def input_int_digits(prompt, digits=4):
while True:
s = input(prompt).strip()
if len(s) == digits and s.isdigit():
return int(s)
print("Invalid input -- {}-digit integer expected.".format(digits))

请注意,我使用 str.strip() 删除前导或尾随的空白,并且 str.isdigit() 检查字符串中的所有字符是否都是数字 --你不需要遍历字符串。

关于python - 值错误 : invalid literal for int() with base 10 for non-digits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com