为什么我不能将这个数字作为整数?

时间:2016-11-21 16:30:36

标签: python

我需要比较2个值:列表中的第一个变量和用户的输入。用户的输入已经是整数,但代码不允许我将其他值转换为整数形式。

我已经尝试过" int"," float"和"复杂"只是为了看,但没有成功。

这是我的代码:

Stock = open("stock.txt","r")
Next = False
print("Products avaliable are: ")
for loop in range (10):
    StockProduct = Stock.readline()
    product = StockProduct.split("\t")
    print(product[0] , product[1])
while Next != True:
    USERproduct = int(input("Which product did you buy? "))
    Amount = int(input("How many did you buy? "))
    for loop in range (10):
        StockProduct = Stock.readline()
        product = StockProduct.split("\t")
        productONE = product[0]

        if USERproduct == int(productONE) :
            USER2 == product
            print(USER2)
            Next = True
        else:
           USERproduct = int(input(" 2 Which product did you buy? "))
         #   Amount = int(input("2 How many did you buy? "))

,输出为:

Traceback (most recent call last):
  File "C:\Users\User\Documents\Task 3.py", line 20, in <module>
    if USERproduct == int(productONE) :
ValueError: invalid literal for int() with base 10: ''
>>> 

这是针对学校的受控评估。

1 个答案:

答案 0 :(得分:0)

我认为你可以让你的程序进行两项更改。首先,不要将读取限制为10行,而是遍历文件。其次,一旦你浏览了文件,你需要将它倒回到开头或重新打开它。

Stock = open("stock.txt","r")
Next = False
print("Products avaliable are: ")
for StockProduct in Stock:
    product = StockProduct.split("\t")
    print(product[0] , product[1])
while Next != True:
    USERproduct = int(input("Which product did you buy? "))
    Amount = int(input("How many did you buy? "))
    Stock.seek(0)
    for StockProduct in Stock:
        product = StockProduct.split("\t")
        productONE = product[0]

        if USERproduct == int(productONE) :
            USER2 == product
            print(USER2)
            Next = True
        else:
           USERproduct = int(input(" 2 Which product did you buy? "))
         #   Amount = int(input("2 How many did you buy? "))