如何修复“ValueError:invalid literal for int(),基数为10:”

2024-04-25 23:42:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个代码,应该得到如下输入:

4
n hgh hjhgj jhh
1
jghj
3

代码应该得到一个整数n,然后得到第n个字符串。在

^{pr2}$

我希望它能运行,但有这样一个错误: 以10为基数的int()的文本无效:“hj jhg hj” 我不能理解这个问题,因为n是整数,A有字符串,它们之间没有任何关系!请帮我解释一下为什么会这样,我该怎么解决?在


Tags: 字符串代码文本关系错误整数int基数
1条回答
网友
1楼 · 发布于 2024-04-25 23:42:25

您的输入不正确,您的代码要求您在不同的输入中提供字符串,而不是在一行中。为了确保输入询问的是什么,您可以给input一个文本,以便它在控制台中显示:

i =0
A=[[],[],[]]
while i < 3:
    j=0
    n=int(input("n: "))
    while j<n:
        A[i].append((input("> ")))
        j+=1     
    i+=1
print(A)

这样可以得到:

^{pr2}$

另外,当你知道你的循环要迭代多少次,而不是使用while你可以做for,类似这样:

^{3}$

同样的结果;)


编辑:

根据@kabanus的假设,如果您真的想要这种输入,则需要拆分给定的字符串:

A = []
for i in range(3):
    n = int(input("n: "))
    while True:
        words = input("> ").split()
        if len(words) == n:
          break
        print(f"You gave {len(words)} words, you must give {n} words! Try again.")
    A.append(words)
print(A)

这样可以得到:

n: 4
> n hgh hjhgj jhh
n: 1
> jghj
n: 3
> a b c
[['n', 'hgh', 'hjhgj', 'jhh'], ['jghj'], ['a', 'b', 'c']]

添加了一个while循环以继续询问,如果给出的单词数不正确,则会显示一条小消息。在

相关问题 更多 >