【问题标题】:Why does my code only except the last input?为什么我的代码只除了最后一个输入?
【发布时间】:2016-08-23 12:10:14
【问题描述】:

我有一个问题,用户输入各种代码到 1 个变量中,然后我想将这些输入拆分成一个列表。但是,我意识到我的变量只接受最后一个输入,意思是列表出来只有一个代码,而不是几个。如何让变量存储多个输入?

while True:
    itemsneeded = input("How many items do you need?")
    if itemsneeded.isnumeric() and int(itemsneeded) <= 5:
        break
    GTIN = ''
    count = 0
    while count < int(itemsneeded):
        GTIN = (input('Please enter all GTIN-8 for all items'))
        if GTIN.isnumeric() and len(GTIN) == 8:
            Num0 = int(GTIN[0]) * 3
            Num1 = int(GTIN[1])
            Num2 = int(GTIN[2]) * 3
            Num3 = int(GTIN[3])
            Num4 = int(GTIN[4]) * 3
            Num5 = int(GTIN[5])
            Num6 = int(GTIN[6]) * 3
            Num7 = int(GTIN[7])
            total2 = (Num0 + Num1 + Num2 + Num3 + Num4 + Num5 + Num6 + Num7)
            if total2 % 10 == 0:
                print(GTIN)
                if GTIN in open('read_it.txt').read():
                    print('entered GTIN is valid')
                else:
                    print('The code entered is invalid')
                    print('Please renter this code')

            count += 1
        else:
            print("The entered GTIN-8 codes are incorrect")
            print(GTIN)
    lst = GTIN.split()
    print(lst)

我不能使用这个 (Two values from one input in python?) 因为我不知道用户想要多少项目,用户输入的项目可能从 1 到 5 不等。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    创建一个空列表,然后在循环中使用list.append。这将做的是将每个新条目添加到列表的末尾。

    GTIN=''
    #count=0
    items = [] # replaces count = 0
    #while count<int(itemsneeded):
    while len(items) < int(itemsneeded): # replaces other while condition
        ...
            ...
            #count += 1
            items.append(GTIN) # replaces count += 1
        ...
    
    print(items)
    

    在覆盖内置列表方法时,您还应该避免使用list 作为变量名。

    您的代码也不适用于无效输入。如果他们输入的代码不正确,那么它仍然会增加,就好像添加了有效项目一样。您应该将items.append(GTIN) 移动到您检查 GTIN 是否有效的 if 语句中。

    【讨论】:

    • 非常感谢您的回答。
    • 非常感谢您的回答。我是这个 .append() 函数的新手,你能解释一下它的作用以及为什么要检查项目的长度吗?我不会再将列表用作变量;)。另外,我刚刚测试了我的程序,它只需要我的文本文件中的代码,你可以看到我的程序读取我的文本文件以查看用户输入是否匹配。如果你尝试输入任何其他内容,它只会输出代码不正确并循环问题。
    • 我认为最好阅读一些 docs 或 python 教程,而不是解释列表。它们很容易理解,所以只要在 IDLE 中玩弄它们,直到你明白为止。
    【解决方案2】:

    或许对你有帮助:

    nums = input().split()
    int_nums = [ int(x) for x in nums ]
    

    【讨论】:

    • 我将 .split() 添加到第 8 行,问题是现在我得到“'list' object has no attribute 'isnumeric'”,显然我正在使用 isnumeric() 来验证用户输入是一个数字。我也尝试将 int 放在第 8 行而不是使用 isnumeric() ,但我仍然得到同样的错误。
    猜你喜欢
    • 2021-10-13
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多