我从文本文件获取的变量没有定义

daupos2t  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(263)

我将代码写入文本文件的第一组代码是:

water = open ('water.txt','w')

for i in range(4):
    account_number = int(input("Enter account number:"))
    type = input('enter R for residential, B for business: ')
    gallons = int(input('Enter number of gallons:'))
    water.write(str(account_number) + " " + type +" " + str(gallons) + "\n")

water.close()

我从文本文件中读取和计算数据的代码是:

output = open('water.txt', 'r')
for line in output:
    words =line.strip().split()
    account_number = words[0]
    type = words[1]
    gallons = words[2]
    price = 0
    if type =='R':
        if gallons <= '6000':
            price = 0.005 * gallons
        else:
            price = 0.007 * gallons
    else:
        if type =='B':
            if gallons <= '8000':
               price = 0.007 * gallons
            else:
                price = 0.008 * gallons
                print (price)
print('Account Number %s Water charge: $%.2f'% (account_number,price))
output.close()

然而 account_number 以及 price 变量没有定义,我看不出问题所在。

ckocjqey

ckocjqey1#

单词是字符串,因此必须将它们转换为浮点或整数进行比较。我改成了浮子。第二,不能与字符串比较 '6000' . 请看下面的答案。

water = open ('water.txt','w')

for i in range(4):
    account_number = int(input("Enter account number:"))
    type = input('enter R for residential, B for business: ')
    gallons = int(input('Enter number of gallons:'))
    water.write(str(account_number) + " " + type +" " + str(gallons) + "\n")

water.close()

output = open('water.txt', 'r')
for line in output:
    print(line)
    words =line.strip("\n").split(" ")
    print(words)
    account_number = float(words[0]) # converted to float, but can also be integer as well, as int(words[2])
    type = words[1]
    gallons = float(words[2]) # converted to float, but can also be integer as well, as int(words[2])
    price = 0
    if type =='R':
        if gallons <= 6000:  # you cannot compare with string, converted to 6000
            price = 0.005 * gallons
        else:
            price = 0.007 * gallons
    else:
        if type =='B':
            if gallons <= 8000: # you cannot compare with string, converted to 8000
                price = 0.007 * gallons
            else:
                price = 0.008 * gallons
                print (price)

print('Account Number %s Water charge: $%.2f'% (account_number,price))

output.close()
hgtggwj0

hgtggwj02#

如果文件为空,则循环将不会运行,并且 account_number 以及 price 不会被定义。python不能在没有赋值的情况下声明一个变量,赋值肯定会执行。要解决此问题,请在循环之前放置此行:

account_number = price = None

您可能应该检查这些变量中的一个是否仍然存在 None 在运行 print 打电话。

相关问题