2014-11-25 3 views
1

Я ЕСМЬ ПИТОН И КОДИРОВАНИЕ В ОБЩЕМ. Итак, у меня есть программа с меню, в котором есть несколько функций. индивидуально каждая функция работает отлично сама по себе, однако, когда я собираю их вместе, они обычно не выполняются полностью и вместо этого останавливаются на полпути или вообще не работают. ПРИМЕР: функция remove не удаляет то, что я говорю. def show_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 
+0

Пожалуйста получите правильный отступ – biobirdman

+0

В общем случае вы можете использовать 'return' в функции один раз. Может быть несколько операторов 'return', но выполняется только одно. При возврате функция прекратит выполнение. Если вы используете цикл while, из цикла выйдет ответ. –

ответ

0

Вы определяете функции, но это не вызывает функцию. Стандартный способ сделать это в Python - использовать инструкцию if __name__=="__main__": в нижней части файла. Когда файл выполняется (вместо функций/классов, импортируемых другим скриптом), выполняется блок кода в пределах if __name__=="__main__":.

Получить комфортно с этим, это полезно и чистый :) Хорошо читать - What does if __name__ == "__main__": do?

Так, к примеру ...

В нижней части файла ...

if __name__=="__main__": 
    main() 
Смежные вопросы