您正在编写一个具有多个功能的 Python 程序,每个功能在单独运行时都可以正常工作。但是,当您将它们组合在一起时,这些功能通常无法完全执行,或者会中途停止或根本不起作用。例如,remove 函数无法删除您告诉它删除的内容,show_coffee 函数只显示第一个描述和重量,而没有显示其他任何内容。
- 解决方案
为了使这些功能能够完全执行,您需要确保它们在程序中被正确调用。具体来说,您需要确保以下几点:
-
首先,您需要确保在程序中正确调用这些函数。例如,您需要确保在
main函数中调用process_choice函数,并在process_choice函数中调用其他函数。 -
其次,您需要确保这些函数的参数正确。例如,您需要确保在调用
add_coffee函数时传递正确的参数,并在调用show_coffee函数时传递正确的参数。 -
最后,您需要确保这些函数在程序中被正确使用。例如,您需要确保在适当的时候调用
add_coffee函数,并在适当的时候调用show_coffee函数。
下面是您需要做的具体步骤:
- 首先,在
main函数中调用process_choice函数。
def main():
choice = ''
fun = []
while choice != 4:
menu()
choice = getUserChoice()
if choice != 4:
fun = process_choice(choice, fun)
print(fun)
print("Goodbye!")
- 其次,在
process_choice函数中调用其他函数。
def process_choice(choice, fun):
if choice == 0:
fun = add_coffee(fun)
elif choice == 1:
fun = show_coffee(fun)
elif choice == 2:
fun = search_coffee(fun)
elif choice == 3:
fun = modify_coffee(fun)
else:
print(choice, "is not a valid choice.")
return fun
- 最后,在程序中正确使用这些函数。例如,您需要确保在适当的时候调用
add_coffee函数,并在适当的时候调用show_coffee函数。
以下是您需要做的具体步骤:
- 在
add_coffee函数中,您需要确保正确地打开和写入咖啡文件。
def add_coffee(fun):
another = 'y'
coffee_file = open('coffee.txt', 'a')
Description = {}
while another == 'y' or another == 'Y':
print('Enter the following coffee data:')
descr = input('Description: ')
qty = int(input('Quantity (in pounds): '))
coffee_file.write(descr + '\n')
coffee_file.write(str(qty) + '\n')
print("Do you want to add another record?")
another = input("Y=yes, anything else =no: ")
return fun
- 在
show_coffee函数中,您需要确保正确地打开和读取咖啡文件。
def show_coffee(fun2):
coffee_file = open('coffee.txt', 'r')
descr = coffee_file.readline()
while descr != "":
qty = str(coffee_file.readline())
descr = descr.rstrip('\n')
print('Description:', descr)
print('Quantity:', qty)
descr = coffee_file.readline()
fun = fun2
return fun
- 在
search_coffee函数中,您需要确保正确地打开和读取咖啡文件。
def search_coffee(fun3):
found = False
search = input('Enter a description to search for: ')
coffee_file = open('coffee.txt', 'r')
descr = coffee_file.readline()
while descr != '':
qty = float(coffee_file.readline())
descr = descr.rstrip('\n')
if descr == search:
print('Description:', descr)
print('Quantity:', qty)
found = True
descr = coffee_file.readline()
fun = fun3
return fun
- 在
modify_coffee函数中,您需要确保正确地打开和读取咖啡文件。
def modify_coffee(fun4):
found = False
search = input('Which coffee do you want to delete? ')
coffee_file = open('coffee.txt', 'r')
temp_file = open('temp.txt', 'w')
descr = coffee_file.readline()
while descr != '':
qty = float(coffee_file.readline())
descr = descr.rstrip('\n')
if descr != search:
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
else:
found = True
descr = coffee_file.readline()
fun = fun4
return fun