I am creating a POS system in Python, which is almost complete. (GUI not included). However, I want to be able to store the items that a user registers.
I tried saving the object to a file, but that did not help:
with open('myObject.pkl', 'wb') as outp:
itemObject = Item("", 0, 0)
pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)
Even after I input the item's details ("name",price,stock) an exit the program, when I started it again I had to register the item all over again.
I also searched online on the matter, but all the results I got did not support updating the attributes of the object in the file.
I've also checked more examples on the forum, but none of them suit my needs well, like this one: Saving an Object (Data persistence), Python- Saving list of objects and its attributes
If it helps, here is where I defined the class and object:
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
itemObject = Item("", 0, 0)
Here is the function that updates the class attributes based on user input:
def regItem():
name = input("What is your item called? ")
name.lower()
if name == 'exit':
exit()
try:
price = int(input("How much does it cost? "))
name.lower()
if name == 'exit':
exit()
if (isinstance(price, int)):
stock = input("How much stock is available for this item? ")
name.lower()
if name == 'exit':
exit()
itemObject.name = name
itemObject.price = price
itemObject.stock = stock
int(itemObject.price)
int(itemObject.stock)
print("Item",itemObject.name,"priced at",itemObject.price,"with available stock of",itemObject.stock,"has been registered")
start()
except ValueError:
print("Must be a number")
regItem()
I'm learning Python as my first language, and I'm also new to stack overflow. Any help would be appreciated. Thanks in advance.
You need to conditionally load the object you are trying to persist.
import os
import pickle
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __str__(self):
return f"Item {self.name} priced at {self.price} with available stock of {self.stock}"
def regItem():
name = input("What is your item called? ")
name.lower()
if name == 'exit':
exit()
try:
price = int(input("How much does it cost? "))
name.lower()
if name == 'exit':
exit()
if (isinstance(price, int)):
stock = input("How much stock is available for this item? ")
name.lower()
if name == 'exit':
exit()
itemObject = Item(name, price, stock)
print(f"{itemObject} has been registered")
return itemObject
except ValueError:
print("Must be a number")
return regItem()
def start(obj):
print("Starting {}".format(obj))
def main():
filename = 'myObject.pkl'
if os.path.exists(filename):
with open(filename, 'rb') as inp:
itemObject = pickle.load(inp)
else:
itemObject = regItem()
with open('myObject.pkl', 'wb') as outp:
pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)
start(itemObject)
main()
Run this once to enter in the data. Run it again and it will start with the same object you started with.
Related
So the prompt is:
Phase 1: Employee Class
Write a class named Employee that holds the following data about an employee in attributes: name, ID Number, department, and job title.
Once you have written the class, write a program that creates three Employees objects to hold the following data:
Name, ID Number, Department, Job Title
Susan Meyers 47899 Accounting Vice President
Mark Jones 39119 IT Programmer
Joy Rodgers 81774 Manufacturing Engineer
The program should store this data in the three objects, then display the data for each employee on the screen.
Phase 2: Employee Management System
This exercise assumes you have created the Employee class for Phase 1. Create a program that stores Employee objects in a dictionary. Use the employee ID number as the key. The program should present a menu that lets the user perform the following actions:
Look up an employee in the dictionary
Add a new employee to the dictionary
Change an existing employee's name, department, and job title in the dictionary
Delete an employee from the dictionary
Quit the program
When the program ends, it should pickle the dictionary and save it to the file. Each time the program starts, it should try to load the pickled dictionary from the file. If the file does not exist, the program should start with an empty dictionary.
SO for the most part I was able to create the class, and I was able to create the menu, I'm having problems with putting the employees in the file and loading so that I can use the menu. Here's my code:
import EmployeeClass
import pickle
def lookup(dictionary):
id_num = input("What is the employee's ID number")
if id_num in dictionary.keys():
print(id_num, ":", dictionary[id_num].str())
else:
print("I'm sorry we don't have that number in our registry. Try again")
lookup(dictionary)
def add(dictionary):
name = input("What is their name?")
id_num = input("What is their ID number?")
department = input("What department do they work in?")
title = input("What position do they hold?")
entry = EmployeeClass.Employee(name, id_num, department, title)
dictionary[id_num] = entry
return dictionary
def change(dictionary):
id_num = input("Enter the ID Number off the employee you would like to change:")
if id_num in dictionary.keys():
tempID = id_num
newName = input("What would you like to change the name to?")
newID = input("What would you like to change their ID Number to?")
newDepartment = input("What department does this person work in?")
newTitle = input("What title does this person hold?")
entry = EmployeeClass.Employee(newName, newID, newDepartment, newTitle)
dictionary[newID] = entry
del dictionary[tempID]
print("Employee changed successfully")
else:
print("Employee not found. Try again")
def delete(dictionary):
id_num = input("Enter the ID Number of the employee that would like to delete")
if id_num in dictionary.keys():
del dictionary[id_num]
else:
print("That employee was not found")
def save_close(dictionary):
output_file = open('employee.dat', 'wb')
pickle.dump(dictionary, output_file)
output_file.close()
def main():
employee_data = open("employee.dat", 'wb')
emp1 = EmployeeClass.Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = EmployeeClass.Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = EmployeeClass.Employee("Joy Rodgers", 81774, "Manufacturing", "Engineer")
pickle.dump(emp1, employee_data)
pickle.dump(emp2, employee_data)
pickle.dump(emp3, employee_data)
employee_data.close()
input_file = open('employee.dat', 'rb')
pickle.load(input_file)
input_file.close()
employee_dictionary = {}
next = True
while next:
print("Welcome to the the Employee Management System. Would you like to:\n")
print("Lookup an employee? Press 1 \n")
print("Add a new employee? Press 2 \n")
print("Alter an existing employee? Press 3 \n")
print("Delete an existing employee's information? Press 4 \n")
print("Save and Close? Press 5 \n")
user_choice = input(int())
menu = {"1": lookup, "2": add, "3": change, "4": delete, "5": save_close}
x = menu[user_choice](employee_dictionary)
if user_choice == 2:
employee_dictionary.update(x)
if user_choice ==3:
employee_dictionary.update(x)
if user_choice ==4:
employee_dictionary.update(x)
main()
So luckily I was able to figure out the pickling problem thanks to someone who answered, but after that when loading the menu it says that my Employee object has not attribute keys. Thank you for your responses!
What you're doing wrong is you're not assigning the depickled file to any variable.
You need to change this block of code
input_file = open('employee.dat', 'rb')
pickle.load(input_file)
input_file.close()
employee_dictionary = {}
to
input_file = open('employee.dat', 'rb')
employee_dictionary=pickle.load(input_file)
input_file.close()
Only then would you be able to access the pickled dictionary.
I'm looking at this example and I want to figure out how can I search up a name instead of the ID, then display all the information for the name? For example if it has the ID of 1, name: Bob, department: sales, and job title: manager. If we search up "Bob", everything will display. Sorry this is long.
class Employee:
def __init__(self, name, ID, department, job_title):
self.__name = name
self.__ID = ID
self.__dept = department
self.__job = job_title
def set_name(self, name):
self.__name = name
def set_department(self, department):
self.__dept = department
def set_job_title(self, job_title):
self.__job = job_title
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID
def get_department(self):
return self.__dept
def get_job_title(self):
return self.__job
def __str__(self):
return 'Name: ' + self.__name + '\n' + \
'ID Number: ' + str(self.__ID) + '\n' + \
'Department: ' + self.__dept + '\n' + \
'Job Title: ' + self.__job
import pickle
def pickle_it(employees):
# Open file in binary write mode
output_file = open('employees.dat', 'wb')
# Write the data to the file
pickle.dump(employees, output_file)
# Close the file
output_file.close()
def unpickle_it():
try:
# Attempt to open file in binary read mode
input_file = open('employees.dat', 'rb')
except IOError:
# If the file doesn't exist, then create it by opening using write
# mode. Then just close and reopen in binary read mode.
file = open('employees.dat', 'wb')
file.close()
input_file = open('employees.dat', 'rb')
# Load the employees dictionary or create an empty dictionary if file is
# empty
try:
employees = pickle.load(input_file)
except:
employees = {}
# Close the file
input_file.close()
# Return the employees dictionary
return employees
import menu_choices
import save_load_dict
# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
employees = save_load_dict.unpickle_it()
choice = menu_choices.get_menu_choice()
while choice != QUIT:
if choice == LOOK_UP:
menu_choices.look_up(employees)
elif choice == ADD:
menu_choices.add(employees)
elif choice == CHANGE:
menu_choices.change(employees)
elif choice == DELETE:
menu_choices.delete(employees)
choice = menu_choices.get_menu_choice()
save_load_dict.pickle_it(employees)
main()
import employee_class
# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def get_menu_choice():
print('\n\033[4m' + 'Employee Directory' + '\033[0m')
print('1. Look up an employee')
print('2. Add a new employee')
print('3. Edit an employee\'s information')
print('4. Delete an employee')
print('5. Quit\n')
# Get the user's choice.
choice = int(input('Enter your choice: '))
# Validate the choice.
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
# return the user's choice.
return choice
# The look_up function looks up an employee and displays their information.
def look_up(employees):
# Get a name to look up.
ID = input('Enter an employee ID number: ')
# Look it up in the dictionary.
if ID in employees:
print(employees[ID])
else:
print('That ID number is not found.')
# The add function adds a new entry into the dictionary.
def add(employees):
# Get employee information.
name = input('Enter the employee\'s name: ')
ID = input('Enter the employee\'s ID number: ')
department = input('Enter the employee\'s department: ')
job_title = input('Enter the employee\'s job title: ')
# If the name does not exist, add it.
if ID not in employees:
employees[ID] = employee_class.Employee(name, ID, department, \
job_title)
else:
print('An entry with that ID number already exists.')
Your question heading asks for how to search using email while the class Employee has no email attribute.
To search using other attribute like Name:
Though the code snippets you pasted doesn't define what employees object is, it's a dict mapping between id and corresponding Employee object.
If you only need to search by name, you can make the employees dictionary as a mapping between Name and Employee objects (list, as multiple employee can have same name).
If you need a more dynamic solution that lets you search by just about anything, then you need to match with all attributes of each Employee object. And also will need to take care of case insensitivity in search.
def look_up(employees):
# Get any searchtext to lookup
searchtext = input('Enter search query to lookup')
matches = [emp for emp in employees.values()
if searchtext.lower() in [
emp.get_name().lower(),
emp.get_ID_number(), # Add .lower() if needed
emp.get_department().lower(), #.lower() for case insensitive match
emp.get_job_title().lower()
]
]
if not matches:
print(f'No employee matches any attribute for searchtext {searchtext}')
return None
# If there are valid matches
print(matches)
Eliminate any of the above fields if not needed.
You can go more crazier in terms of matching the string with partial matches like doing searchtext in candidate for candidate in [emp.<some_attributes>,..] or use levenshtein distance.
You'll need to take into account that two employees could have the same name. The following code (adapted from your existing look_up function) will return all the employees with the name specified, or a message that there are no employees with that name :
# The look_up function looks up an employee by name and displays their information.
def look_up_by_name(employees):
# Get a name to look up.
name = input('Enter an employee Name: ')
matches = [emp for emp in employees if emp['name'] == name]
if len(matches) == 0:
print('No employees with name "{}" found'.format(name))
else:
for m in matches:
print(m)
Basically I am making an app to better assist me at managing my ebay store. I am still very new to programming and OOP. After watching some tutorials I pieced together the following code. Everything so far works pretty well. What I am currently stuck on is when the user inputs an item for inventory, it is not saving it. And, when the user wants to view the inventory the item they added wont populate. Any input or suggestions would be much apprenticed.
def Inventory():
All_Inventory = {}
class Ebay_Inventory:
def __init__(self, manufacturer, object_type, price):
self.manufacturer = manufacturer
self.object_type = object_type
self.price = price
def add_item(self):
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item_info = Ebay_Inventory(manufacturer, object_type, price)
All_Inventory = item_info
print("Item added successfully")
def delete_item(self):
delete = input("What is the item you want to delete?: ")
if delete in All_Inventory.keys():
del[delete]
print("The item entered has been deleted.")
else:
print("Item not found")
def sale_status(self):
update = input("What is the item you want to update?:")
if update in All_Inventory.keys():
pass
else:
print("Item not found")
user=True
while user:
print("\n1. Add to item inventory")
print("2. Remove item from inventory")
print("3. Update sale status")
print("4. View inventory")
print("5. Exit program")
user_wants=input("What would you like to do today?")
if user_wants=="1":
Ebay_Inventory.add_item(input)
elif user_wants=="2":
Ebay_Inventory.delete_item(input)
elif user_wants=="3":
Ebay_Inventory.sale_status(input)
elif user_wants=="4":
print(All_Inventory)
elif user_wants=="5":
print("\n Thank you for using item inventory.")
break
elif user_wants!="":
print("\n Input not understood. Please try again.")
You need to read about Scope, OOP and dicts:
You are not adding to your Inventory.All_Inventory - you create a new local with All_Inventory = item_info
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
Short description of the scoping rules?
You mix up static class attributes and instance attributes, read:
https://docs.python.org/3/tutorial/classes.html#class-objects.
What is the difference between #staticmethod and #classmethod?
You are deleting / accessing your dictionary wrongly - see :
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Delete an element from a dictionary
Fixed:
class Ebay_Inventory:
Inventory = {} # class property
#staticmethod
def print_inventory():
for k in Ebay_Inventory.Inventory:
for i in Ebay_Inventory.Inventory[k]:
print(k,i)
class Ebay_Item:
def __init__(self, key, manufacturer, object_type, price):
self.manufacturer = manufacturer
self.object_type = object_type
self.price = price
self.key = key
def __str__(self):
return f"{self.manufacturer} {self.object_type} {self.price}"
def __repr__(self):
return str(self)
#staticmethod
def add_item(key=None, man=None, obj=None, pri=None):
# use values if given, else ask - this is for demo purposes only
key = key or input("Enter key: ")
manufacturer = man or input("Enter Manufacturer: ")
object_type = obj or input("Enter what the item is: ")
price = pri or input("Enter price: ")
# create new item
item_info = Ebay_Inventory.Ebay_Item(key, manufacturer, object_type, price)
# add to class member, create key if need be
Ebay_Inventory.Inventory.setdefault(item_info.key,[]).append(item_info)
def delete_item(key=None):
delete = key or input("What is the item you want to delete?: ")
if delete in Ebay_Inventory.Inventory:
del Ebay_Inventory.Inventory[delete]
print("The item entered has been deleted.")
else:
print("Item not found")
def __str__(self):
return Ebay_Inventory.print_inventory()
# add 2 items and print
Ebay_Inventory.add_item(1,"Me","Me",1000)
Ebay_Inventory.add_item(2,"You","You",1000)
Ebay_Inventory.print_inventory()
# remove non existent and existent item and print
Ebay_Inventory.delete_item(3)
Ebay_Inventory.delete_item(2)
Ebay_Inventory.print_inventory()
Output:
1 Me Me 1000
2 You You 1000
Item not found
The item entered has been deleted.
1 Me Me 1000
Sorry to rework your code pretty extensively, but I think this is more like what you are going for:
class EbayInventory:
def __init__(self):
self.all_inventory = []
def print_items(self):
print('Current item list by index:')
for i in range(0, len(self.all_inventory)):
print("{} -> {}".format(i+1, self.all_inventory[i]))
def add_item(self):
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
self.all_inventory.append(item)
print("Item added successfully")
def delete_item(self):
self.print_items()
delete = int(input("Item id you want to delete: "))
try:
del self.all_inventory[delete - 1]
print("The item entered has been deleted.")
except Exception as e:
print("An error occurred deleting that item, details below")
print(e)
def sale_status(self):
self.print_items()
update_index = int(input("Item id you want to update: "))
if update_index > len(self.all_inventory) or update_index <= 0:
print("You're trying to change an item that doesn't exist!!")
return
print("OK. Let's get that item up to date!")
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
self.all_inventory[update_index - 1] = item
print("OK. We got that update taken care of")
if __name__ == "__main__":
my_app = EbayInventory()
while True:
print("\n1. Add to item inventory")
print("2. Remove item from inventory")
print("3. Update sale status")
print("4. View inventory")
print("5. Exit program")
user_wants = input("Please enter the number corresponding to how you would like help: ")
if user_wants == "1":
my_app.add_item()
elif user_wants == "2":
my_app.delete_item()
elif user_wants == "3":
my_app.sale_status()
elif user_wants == "4":
my_app.print_items()
elif user_wants == "5":
print("Thank you for using item inventory.")
break
else:
print("Input not understood. Please try again.")
You had a variable user that did nothing. You can simply enter an infinite loop with while True:. If you wanted to loop the way you did, then instead of a break you could have put a user = False to break out of the loop. This is sometimes a nifty trick, but doesn't make sense here I think. It seemed to me the inventory was really the only thing that would benefit by being stored in your class, and the methods could then access it to adjust it via a self.all_inventory. I moved your code to ask for item inputs to the add_item() and sale_status() methods, so now the main block of code looks a lot cleaner. I also wrapped it in if __name__ == "__main__": so that you can import this class to another project without running the entire program! I threw in some basic error checking with try: and except: clauses also. I think you were misunderstanding the difference between a Class and an Instance. So in my code the Class is EbayInventory, but the Instance is my_app. You create instances of your class just like I did with my_app = EbayInventory() and then the self now refers to my_app. In this manner I can call my_app.add_item(). You can have several instances of objects though, and they each have their own space in your computers memory. So you could have said:
app1 = EbayInventory()
app2 = EbayInventory()
app1.add_item()
And only the app1 will have any items, whereas app2 is still an empty list, but still has the methods to build an inventory via app2.add_item(). To answer your main question though, you never call your function Inventory() and therefore it doesn't exist to hold your information. When you call item_info = Ebay_Inventory(manufacturer, object_type, price) in fact you are making an Instance of a class, which is really nonsensical to do here because that means on the next line you could say item_info.add_item() and this would make another instance, yet you are not saving this information anywhere so you can never retrieve it!
I'm trying to make a program that creates objects from another class I made and calls the class methods based on user input. The problem I'm having is that once a object is created I'm trying to enter that object into a dictionary, so I can compress it with pickle for later use. I'm having trouble trying to find the best way to append these class objects into a list when the name for the created objects are the same as the name variable I prompt from the user. The lines I am talking about are lines 34 to 41. I have so far change it to set the object named personObject to create a object and repeat if another user is created. It seems to work, I just feel there is a better way.
from budgetaccount import *
import pickle
import sys
class mainprogram:
def __init__(self):
self.account_list = {}
self.name = ""
def main(self):
grab_user()
endProgram = 0
while endProgram != 6:
print('Welcome to our monthly budget program\n')
print('1-Create a new account')
print('2-Exit')
selection = input("Enter your Selection: ")
if selection != "":
choice = int(selection)
if choice == 1:
self.create_user()
if choice == 2:
break
continue
name = self.account_list[0]
name.showSetBudgetLimits()
def create_user(self):
cancel = False
while (True):
self.name = input("Type your username: ")
name = self.name
income = float(input("Enter your income: "))
personObject = BudgetAccount(name, income)
personObject.setUserExspenseLimit()
self.account_list.append({
"%s"% (name) : personObject
})
cont = input("Want to add another? (Y/N)")
if cont == "N":
break
continue
print(self.account_list)
self.pickle_data1()
def pickle_data1(self): ###Pickle writes to userdata1.pickle from account_list###
pickle_out = open("userdata1.pickle", "wb")
pickle.dump(self.account_list, pickle_out)
pickle_out.close()
def grab_user():
pickle_in = open("E:/Python/Lib/idlelib/userdata1.pickle","rb")
account_list = pickle.load(pickle_in)
print(account_list)
print(account_list)
test = ihateThis()
test.main()
i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.