我将代码写入文本文件的第一组代码是:
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
变量没有定义,我看不出问题所在。
2条答案
按热度按时间ckocjqey1#
单词是字符串,因此必须将它们转换为浮点或整数进行比较。我改成了浮子。第二,不能与字符串比较
'6000'
. 请看下面的答案。hgtggwj02#
如果文件为空,则循环将不会运行,并且
account_number
以及price
不会被定义。python不能在没有赋值的情况下声明一个变量,赋值肯定会执行。要解决此问题,请在循环之前放置此行:您可能应该检查这些变量中的一个是否仍然存在
None
在运行print
打电话。