完全完成一项功能



我是PYTHON和编码的新手。所以我有一个程序,里面有一个菜单,里面有多个功能。每个功能单独运行都很好,但当我把它们放在一起时,它们通常不会完全执行,而是中途停止或根本无法工作。示例-函数remove不会删除我告诉它的内容。defshow_coffee将只显示第一个描述和权重,而不显示其他内容。我该怎么做才能使函数完全执行?

import os
def main():
choice =''
fun=[]
while choice != 4:
menu()
choice=getUserChoice()
if choice !=4:
fun=process_choice(choice,fun)
print(fun)
print("Goodby!")
def process_choice(choice,fun):
#fun=fun1
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

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

coffee_file.close()
print('Data append to coffee.txt.')

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
coffee_file.close()
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
coffee_file.close()
if not found:
print('That item was not found in the file.')


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
coffee_file.close()
temp_file.close()
os.remove('coffee.txt')
os.rename('temp.txt', 'coffee.txt')
if found:
print('The file has been update.')
else:
print('The item was not found in the file.')


def menu():
print('''
0. Add or Update an entry
1. Show an entry
2. Search
3. remove
4. Remove number
''')

def getUserChoice():
choice=-1
while choice <0 or choice > 3:
print("Please select 0-3: ",end='')
choice=int(input())
return choice

您正在定义函数,但这并不调用函数。在Python中执行此操作的标准方法是在文件底部使用if __name__=="__main__":语句。当文件被执行时(而不是由另一个脚本导入函数/类),if __name__=="__main__":范围内的代码块被执行。

对此感到舒服,它既有用又干净:)读得好-如果__name__=="怎么办__main__":做

例如。。。

在你文件的底部。。。

if __name__=="__main__":
main()

最新更新