Python3.6中的输入错误

问题描述 投票:-3回答:1
t = int(input())
while t:
    qu , pt = input().split(' ')
    qu = int(qu)
    pt = int(pt)
    sd = []
    for i in range(0,qu):
        x = int(input())  # I think I am getting problem in this part of 
        sd.append(x)
    hd , cw = 0 , 0
    diff = pt / 10
    cwk = pt / 2
    for i in range(0,qu):
        if sd[i] <= diff:
            hd += 1
        else:
            if sd[i] >= cwk:
            cw += 1
    if hd == 2 and cw == 1:
        print ('yes')
    else:
        print('no')
    t -= 1

当我尝试输入像'1 2 3'这样的输入时,我得到一个像这样的错误

Traceback (most recent call last):
  File "C:/Users/Matrix/Desktop/test.py", line 8, in <module>
    x = int(input())
ValueError: invalid literal for int() with base 10: '1 2 3'

为什么我会看到这个问题?我该如何纠正这个?

python-3.x user-input
1个回答
0
投票

问题是你传递的是字符串而不是整数。当您键入“1 2 3”时,您会留下空格,这些空格被视为字符。空格不能作为整数转换。如果您将输入设置为数字空间编号空间编号空间,那么我建议您将空白处的句子拆分为一个列表。

def setence_splitter(user_input):
# splits the input
words = text.split()

现在你有了列表,单词,每个单独的编号。您可以使用单词索引来调用每个单独的数字。第一个数字是单词[0],依此类推。

© www.soinside.com 2019 - 2024. All rights reserved.