2 回答
TA贡献1794条经验 获得超7个赞
两件事情。什么都没有出现的原因是因为您在检查业务类型的 while 循环中陷入了无限循环。将其更改为 if 语句可修复它。
此外,当您使用 and、or 或其他一些运算符时,您必须再次指定要比较的变量。
读取文件行的 while 语句应如下所示:
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
if business_type == 'b' or business_type =='B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
if business_type == 'r' or business_type =='R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water charge:$", water_charge)
line = input_file.readline()
输出:
('Account number:', 3147, 'Water charge:$', 5.0)
TA贡献1993条经验 获得超5个赞
主要问题是您的while循环应该是简单的if语句:
if business_type.lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
# So you don't get a NameError for no water_charge
water_charge = 0
你之所以while循环永远无法终止的原因有二:你没读过的下一行内即内环和填充绳状'b'将评估一样True:
# Strings with content act like True
if 'b':
print(True)
# True
# empty strings act as False
if not '':
print(False)
# False
在str.lower()将小写的字符串,这样'R'.lower()的回报'r'。否则没有break条件,while它将永远旋转。
其他一些建议:
1)打开文件时,使用with无需显式open和close文件:
with open('somefile.txt', 'r') as fh:
# Everything else goes under the with statement
2)fh.readline()不需要显式调用,因为您可以直接遍历打开的文件:
with open('somefile.txt', 'r') as fh:
for line in fh:
# line is the string returned by fh.readline()
这也将在fh为空时终止,或者您到达文件的末尾,''当文件为空时您可能不会明确获得,并且您不再需要while循环
3)这通常是不好的做法(但也很难维护)幻数代码。例如,如果帐号没有正好 5 个字符怎么办?一个更简洁的方法是 with str.split(' '),它将在空格上拆分:
with open('somefile.txt', 'r') as fh:
for line in fh:
# This will split on spaces returning a list
# ['3147', 'R', '1000'] which can be unpacked into
# the three variables like below
account_number, business_type, gallons = line.split(' ')
# rest of your code here
总共:
# use with for clean file handling
with open('somefile.txt', 'r') as fh:
# iterate over the file directly
for line in fh:
# split and unpack
account_number, business_type, gallons = line.split(' ')
# enforce types
gallons = float(gallons)
# .strip() will remove any hanging whitespace, just a precaution
if business_type.strip().lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.strip().lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
water_charge = 0.0
print("Account number:", account_number, "Water charge:$", water_charge)
添加回答
举报