list of lists to find an element from user input - python-3.x

right now, I'm trying to do a simple program, where user can add new, view, search, and delete. But as for now, I'm stuck at def findEmp(): below is my code and I'm really appreciate for you guys to help me with this problem.
When I key in the existing name 'mia' from global list, the result show 'Employee name not exist'.
from tabulate import tabulate
emps_global = [['mia','hr','admin']] # existing element
tablehead = ['Name', 'Department', 'Position']
def addnew():
emp_new = [] # empty local list
emp_new.append(input("Enter name: "))
emp_new.append(input("Enter department: "))
emp_new.append(input("Enter position: "))
emps_global.append(emp_new) # append local list to global list called emps_global
print(emps_global) # print out list of lists for emps_global
def findEmp():
emp = input("Enter employee name: ") # even existing name in the global list show 'not exist'
if emp in range(len(emps_global)): # i'm not sure this is correct or not
print("Yes employee exist")
elif emp not in range(len(emps_global)):
print("Employee name not exist")
def view():
print(tabulate(emps_global, headers=tablehead, tablefmt='psql'))
def deleteInfo():
pass
while True:
print("[1] to add")
print("[2] to search")
print("[3] to view")
print("[4] to delete")
inp = input(">> ")
if inp == '1':
addnew()
elif inp == '2':
findEmp()
elif inp == '3':
view()
elif inp == '4':
deleteInfo()
else:
print("Wrong input")

Edit you findEmp() as
def findEmp():
emp = input("Enter employee name: ") # even existing name in the global list show 'not exist'
for entry in emps_global:
if entry[0]==emp: # i'm sure this is correct or not
return entry
return "Name does not exist"
the range(len(emp_globs)) gives a list of numbers from 0 to len(emp_globs), so your condition compares the input name with a number, hence it doesn't work.

Related

Python Key error -when trying to use statements

Here is my code i am getting a key error on line 31, something to do with the word 'Reserved'
#Create a loan class that will allow members to borrow books
class Loan(Book, Member):
"""Class that allows members to reserve,cancel reservations, return and borrow books
Librarians can extract the data
pre-conditions: inherits from Book and member classes
if the above is not correct the data wont be
"""
#classmethod
#set up a class in order to borrow a book
def Borrow(cls, name, title):
"""
Parameters
----------
cls : TYPE
"""
#Find ID of book/member
BookID = Book.scan(title)[0]
MemberID = Member.scan(name)[0]
#check if the book is available
Status = books[BookID]['Available']
#if the book is available check then check the different reservations
if Status == "Yes":
#if the book is not reserves then issue the book and add a new entry
if books[BookID]["Reserved"] == "No": #THIS IS LINE 31
dateToday = datetime.datetime.now().strftime('%Y-%m-%d')
loans[len(loans)+1]={'BookID':BookID, 'MemberID':MemberID, 'Date of loan': dateToday, 'Date of return':'NaN', 'Length of borrow':'NaN'}
books[BookID]["Available"] = "No"
print("You have now borrowed", title)
#if the books is reserved and the member is first in the queue
#remove the member from the reservation list and record new record
elif books[BookID]["Reserved"] == "Yes" and books[BookID]["ReservedID"][0] == MemberID:
dateToday = datetime.datetime.now().strftime('%Y-%m-%d')
loans[len(loans)+1] = {'BookID':BookID, 'MemberID':MemberID, 'Date of loan': dateToday, 'Date of return':'NaN', 'Length of borrow':'NaN'}
books[BookID]["Available"] = "No"
Loan.RemoveReservation(name, title)
if len(books[BookID]["ReservedID"]) == 0:
books[BookID]["Reserved"] = "No"
print("You have now borrowed", title)
#if the member has reserved the book but there is someone else renting it
elif books[BookID]["Reserved"] == "Yes" and MemberID in books[BookID]["ReservedID"]:
print(title, "is not available at the moment. You can reserve this though")
#if the book isnt available and the member hasnt reserved it
else:
print(title, "is not available")
#
#
elif Status == "No":
if MemberID in books[BookID]["ReservedID"]:
print(title, "not ready")
else:
print(title, "not ready")
Loan.Borrow(name="Charlie Roberts", title ="God Created the Integers")
print(books[Book.scan("God Created the Integer")[0]])
print(loans[len(loans)])
A KeyError means that that key does not exist in the dictionary. If you want to check for existence of a key, either wrap it in a try/catch:
try:
doSomething(myDict['invalidKey'])
except KeyError:
#Process error
OR
Check if the key exists first:
d = {"a": 1, "b": 2}
if "a" in d.keys():
#The key was in the dictionary
else:
#The key wasn't in the dictionary
If you want to add the key to your dictionary, you'll have to set the key equal to a value first:
>>> d = {}
>>> d['a']
KeyError
>>> d['a'] = "foo"
>>> d['a']
foo

Trouble with reading a dictionary file

Hi my assignment is to read the company names and the shorten names of the companies.
This file with tickers below is given:
ticker_symbol.txt
YAHOO:YHOO
GOOGLE INC:GOOG
Harley-Davidson:HOG
Yamana Gold:AUY
Sotheby's:BID
inBev:BUD
So I need to make 3 functions: def tickers_to_dict(filename), def name_to_symbol(name, ticker_dict) and def symbol_to_name(symbol, ticker_dict).
In the function tickers_to_dict(filename), I need to convert the text file into a dictionary and return it which I have done succesfully.
In the functions def name_to_symbol(name, ticker_dict) and def symbol_to_name(symbol, ticker_dict), I need to find the ticker symbol in the dictionary by the input of the company name and the reverse. (by a input of a ticker symbol it needs to find the company name). But I dont know how to solve this two functions. Can someone help me? So far I have this:
def tickers_to_dict():
ticker_dict = {}
bestand = open('ticker_symbol.txt', 'r')
tickers = bestand.readlines()
for line in tickers:
k, v = line.split(':')
ticker_dict[k] = v
return (ticker_dict)
print(tickers_to_dict())
def name_to_symbol(name, ticker_dict):
output needs to be like this:
Enter Company name: YAHOO
Ticker symbol: YHOO
Enter Ticker symbol: BUD
Company name: inBev
I am not sure this ist what you were looking for but here you go:
def name_to_symbol(mydict):
given_input = input("Enter company name: ")
try:
print("Ticker symbol: ", mydict[given_input])
except:
print("False Input")
def symbol_to_name(mydict):
given_input = input("Enter ticker: ")
for key, value in mydict.items():
if given_input == value:
print("Company name: ", key)
return
print("False Input")
I hope this helped you out. If you want to know how it exactly works, you can let me know.
Also this search is case sensitiv. In the textfile you have quite a mess of uppercase and lowercase. Maybe address that if you want to simplify the use of your programm a bit.
def tickers_to_dict():
ticker_dict = {}
bestand = open('pe_8_4_tickers.txt', 'r')
tickers = bestand.readlines()
for line in tickers:
k, v = line.split(':')
ticker_dict[k] = v
return (ticker_dict)
def name_to_symbol(mydict):
given_input = input("Enter company name: ")
for key, value in mydict.items():
if given_input == key:
print("Ticker symbol:", value)
return
else:
# print("Ticker symbol: )
# except:
print("False Input")
def symbol_to_name(mydict):
given_input = input("Enter ticker symbol: ")
for key, value in mydict.items():
if given_input == value:
print("Ticker symbol:", key)
return
else:
print("False Input")
name_to_symbol(tickers_to_dict())
symbol_to_name(tickers_to_dict())
Athos it didnt work
second def statement returns with false input

Python - How to import a variable in a function from other file?

What I am wondering is how do I pass the variable - element, into the second file? So that I can use this element as a parameter in a function and also a value to define the location of a variable in array later.
Also, the variable - element should have the same value as 'i' both in file 1 and 2.
file 1: This is a part of my program.
def menu():
existAccount = False
element = 0
print("Welcome to STLP Store!")
print("1.Login\n2.Sign Up\n3.Exit")
user = int(input("Enter(1-3): "))
if user == 1:
inputEmail = input("Enter Email: ")
inputPassword = input("Enter Password: ")
for i in range(len(customers)):
if inputEmail == customers[i].getEmail() and inputPassword == customers[i].getPassword():
existAccount = True
element = i
break
if existAccount == False:
print("Incorrect Email/Password")
menu()
loggedInMenu(int(element))
file 2:
Now, if I put 'element' in loggedInMenu() , it will say "unresolved reference 'element'". If I don't, it will say "Parameter 'element' unfilled'.
from STLPStoreMain import *
def AppMenu():
choose = input("Enter:")
if choose == '1':
#customers is a array which contain class objects. getEmail() is a method to access hidding information.
print ("Email:", customers[element].getEmail())
print("Password: " + "*" * len(customers[element].getPassword()))
print ("Bill Address", customers[element].getBillAdd())
print ("Credit Card Number:", customers[element].getCredNum())
AppMenu()
if choose == '6':
loggedInMenu(element)
Passing a value from one file (module) to another.
To address your question of passing a variable from one module to another, I have taken the class approach, where the variable you want file2 to access (element) is a property of file1.
The setup:
Both files are placed into the same directory, which contains an __init__.py file.
On instantiation, file2 creates an instance of file1, which runs your login script, and stores the element property into a class attribute of file2.
Next, the menu is called, and uses the self._element attribute which was created in file1.
Here's the code and it's honestly much simpler than the description seems.
Cleanup Edits:
Additionally, (discard them if you like) I've made a couple of PEP/Pythonic edits to your original code:
Changed the if statement to use the all() function, which tests for all conditions in the list to be True.
Updated code to use pure lower case - except for the class, which is camelcase.
Updated your if existAccount == False: statement to the more Pythonic if not existaccount:.
file1.py
As I don't have access to your customers, a simple _customers dictionary has been added for testing. Throw this away and uncomment your lines which access your customers object.
class StartUp():
"""Prompt user for credentials and verify."""
def __init__(self):
"""Startup class initialiser."""
self._element = 0
self._customers = [{'email': 'a#a.com', 'password': 'a'},
{'email': 'b#b.com', 'password': 'b'},
{'email': 'c#c.com', 'password': 'c'},
{'email': 'd#d.com', 'password': 'd'}]
self.menu()
#property
def element(self):
"""The customer's index."""
return self._element
def menu(self):
"""Display main menu to user and prompt for credentials."""
existaccount = False
print("\nWelcome to STLP Store!")
print("1.Login\n2.Sign Up\n3.Exit")
user = int(input("Enter(1-3): "))
if user == 1:
inputemail = input("Enter Email: ")
inputpassword = input("Enter Password: ")
# for i in range(len(customers)):
# if all([inputemail == customers[i].getemail(),
# inputpassword == customers[i].getpassword()]):
for i in range(len(self._customers)):
if all([inputemail == self._customers[i]['email'],
inputpassword == self._customers[i]['password']]):
self._element = i
existaccount = True
break
if not existaccount:
print("incorrect email/password")
self._element = 0
self.menu()
file2.py
class AppMenu():
"""Provide a menu to the app."""
def __init__(self):
"""App menu class initialiser."""
# Display the startup menu and get element on class initialisation.
self._element = StartUp().element
self._customers = [{'email': 'a#a.com', 'password': 'a', 'addr':
'1A Bob\'s Road.', 'cc': '1234'},
{'email': 'b#b.com', 'password': 'b',
'addr': '1B Bob\'s Road.', 'cc': '5678'},
{'email': 'c#c.com', 'password': 'c',
'addr': '1C Bob\'s Road.', 'cc': '9123'},
{'email': 'd#d.com', 'password': 'd',
'addr': '1D Bob\'s Road.', 'cc': '4567'}]
self.menu()
def menu(self):
"""Provide an app menu."""
choose = input("Enter: ")
if choose == '1':
# customers is a array which contain class objects. getemail() is a method
# to access hidding information.
# print ("email:", customers[element].getemail())
# print("password: " + "*" * len(customers[element].getpassword()))
# print ("bill address", customers[element].getbilladd())
# print ("credit card number:", customers[element].getcrednum())
print('-'*25)
print ("email:", self._customers[self._element].get('email'))
print("password: " + "*" * len(self._customers[self._element].get('password')))
print ("bill address:", self._customers[self._element].get('addr'))
print ("credit card number:", self._customers[self._element].get('cc'))
print('-'*25)
self.menu()
if choose == '6':
# loggedinmenu(element)
print('Not implemented.')
The output:
# Create an instance of the menu and run login.
am = AppMenu()
Welcome to STLP Store!
1.Login
2.Sign Up
3.Exit
Enter(1-3): 1
Enter Email: b#b.com
Enter Password: b
Enter: 1
-------------------------
email: b#b.com
password: *
bill address: 1B Bob's Road.
credit card number: 5678
-------------------------
Enter: 6
Not implemented.

How to search for a nested list by user input of a particular element

Newbie learner here. I have a issue where I'm trying to implement new features into code and getting hung up on how to implement the last set of features.
I'm trying to allow the user to search via one of the attributes - SSN - and pull the associated nested list with that SSN. I'm trying to set the search as a def()function so I can put it in a line of if/elif branches at the latter end of the code. Any help is much appreciated.
Regards,
Web searches, course text, python docs, other forum posts.
# You have to use function arguments and returns. Check my code and you can modify it.
def add_emp(emp_list, num):
for i in range(num): # number of employee variable inputs
employee = []
for attribute in ['Name', 'SSN', 'Phone', 'Email', 'Salary']:
employee.append(str(input(f'{attribute}: ')))
print(f'Employee {i} : ', ' '.join(employee).title()) # print employee information
emp_list.append(employee)
# and when you finish, all employee are here
# Next, user request list info
def choose_list(emp_list):
print("You can pull an individual's list by entering 1 - 5")
query_emp_list = int(input("Choose 1 - 5: ")) -1
if 0 <= query_emp_list < len(emp_list):
print(' '.join(emp_list[query_emp_list]))
# section for new format I'm having issue with
def new_emp_format(emp_list):
for employee in emp_list:
[Name, SSN, Phone, Email, Salary] = employee
print(f"---------------------------- {Name} -----------------------------")
print(f'SSN: {SSN}')
print(f'Phone: {Phone}')
print(f'Email: {Email}')
print(f'Salary: {Salary}')
def main():
# user instructions to begin creating list
print('Please enter your Employee information in the below prompts')
emp_list = []
num_emp = int(input("How many Employee's do you want to add? "))
add_emp(emp_list, num_emp)
choose_list(emp_list)
# Beginning of While loop
while(True):
if(input("Do you need another list? (y/n): ")=='y'): # retry request loop
choose_list(emp_list)
continue
elif(input("Want to know how many employees there are? (y/n): ")=='y'):
print('There are', len(emp_list), 'employees in the system.')
continue
elif(input("Would you like to add another Employee? (y/n): ") =='y'):
add_emp(emp_list, 1)
continue
elif(input("Would you like to view all lists in new format? (y/n): ") =='y'):
new_emp_format(emp_list) # output current nested lists in new format
continue
elif(input("Would you like to search employee by SSN? (y/n): ") =='y'):
#section to add in new search via SSN
print('')
continue
else:
break
if __name__== "__main__":
main()
Expected results should look like this after user query of either all the lists or a single nested list
---------------------------- Mike Smith -----------------------------
SSN: 123123123
Phone: 111-222-3333
Email: mike#g'mail.com
Salary: $6000
current output is the base list structure:
[Mike Smith, 123123123, 111-222-3333, mike#g'mail.com, $6000]
You have to use function arguments and returns. Check my code and you can modify it.
def add_emp(emp_list, num):
for i in range(num): # number of employee variable inputs
employee = []
for attribute in ['Name', 'SSN', 'Phone', 'Email', 'Salary']:
employee.append(str(input(f'{attribute}: ')))
print(f'Employee {i} : ', ' '.join(employee).title()) # print employee information
emp_list.append(employee)
# and when you finish, all employee are here
print(emp_list)
return emp_list
# for additional employees
#def add_extra_emp():
# for i in range(1): # number of employee variable inputs
# employee = []
# for attribute in ['Name', 'SSN', 'Phone', 'Email', 'Salary']:
# employee.append(str(input(f'{attribute}: ')))
# print(f'Employee {i} : ', ' '.join(employee).title()) # print employee information
# emp_list.append(employee)
# Function is duplicated with add_amp, so it doesn't needed
# Next, user request list info
def choose_list(emp_list):
print("You can pull an individual's list by entering 1 - 5")
query_emp_list = int(input("Choose 1 - 5: ")) -1
if 0 <= query_emp_list < len(emp_list):
print(' '.join(emp_list[query_emp_list]))
# section for new format I'm having issue with
def new_emp_format(emp_list):
for employee in emp_list:
[Name, SSN, Phone, Email, Salary] = employee
print(f"---------------------------- {Name} -----------------------------")
print(f'SSN: {SSN}')
print(f'Phone: {Phone}')
print(f'Email: {Email}')
print(f'Salary: {Salary}')
def main():
# user instructions to begin creating list
print('Please enter your Employee information in the below prompts')
emp_list = []
num_emp = int(input("How many Employee you want to add?"))
add_emp(emp_list, num_emp)
choose_list(emp_list)
# Beginning of While loop
while(True):
if(input("Do you need another list? (y/n): ")=='y'): # retry request loop
choose_list(emp_list)
continue
elif(input("Want to know how many employees there are? (y/n): ")=='y'):
print('There are', len(emp_list), 'employees in the system.')
continue
elif(input("Would you like to add another Employee? (y/n): ") =='y'):
add_extra_emp(emp_list, 1)
continue
elif(input("Would you like to view all lists? (y/n): ") =='y'):
new_emp_format(emp_list) # output current nested lists in new format
continue
elif(input("Would you like to search employee by SSN? (y/n): ") =='y'):
#section to add in new search via SSN
print('')
continue
else:
break
if __name__== "__main__":
main()

Need Help: TypeError: 'in <string>' requires string as left operand, not list

I am trying to get my code to give me information such as price of an item if I input the brand "Nike" or anything like that. However, I am getting the error code as the title. Please any help would be appreciated
clothing_brands = [
["544", "Jordan", "Shoes", 200],
["681", "Stussy", "Sweatshirt", 50],
["481", "Obey", "T-Shirt", 30],
["339", "North Face", "Jacket", 80],
["250", "Levis", "Jeans", 40],
["091", "Nike", "Socks", 10],
]
def findClothing(brand):
found = False
for brand in clothing_brands:
if clothing_brands in brand[1]:
found = True
break
if found:
return brand
else:
return None
def printBrand(brand):
print ("\n~~~~Thrift Shop Brands:~~~~")
print ("Item Number:", brand[0])
print ("Brand Name:", brand[1])
print ("Clothing Type:", brand[2])
print ("Price:", brand[3])
if __name__ == "__main__":
print ("\n~~~Welcome to Macklemore's clothing Thrift Shop~~~~")
print ("1) Add a brand you would like to see us carry")
print ("2) What is the brand's clothing type?")
print ("3) What is the price of a particular brand?")
print ("4) What is a brand's information?")
print ("5) Print everything we have in stock")
print ("0) Exit")
while True:
option = input ("Please Select a Menu item.")
if (option == "0"):
break
if (option == "1"):
Item_number = input ("What is the Item Number?")
Brand_name = input ("What is the name of the Brand?")
Clothing_type = input ("What type of clothing is the Brand?")
Price = input ("How much is the item?")
brand = [Item_number, Brand_name, Clothing_type, Price]
clothing_brands.append(brand)
print ("Thank you for your input, We will begin searching to add that item into our inventory")
print (Brand_name, Clothing_type, Price)
print ("Come back in a couple of days to see if we have added the item")
if (option == "2"):
brand = input ("What is the brand you are looking for information on?")
brand = findClothing(brand)
if (brand != None):
print ("The Clothing type of this brand is:", brand[2])
if (option == "3"):
brand = input ("What is the brand you are looking for information on?")
brand = findClothing(brand)
if (brand != None):
print ("The Price of the brand is:", brand[3])
if (option == "4"):
brand = input ("What is the brand you are looking for information on?")
brand = findClothing(brand)
if (brand != None):
printBrand (brand)
else:
print ("Sorry, we do not carry this brand. If you would like for us to search for this brand, Please try option 1!")
if (option == "5"):
for brand in clothing_brands:
print (brand)
Your findClothing method does not use its input parameter (it's overwritten by the loop variable) and is instead using if clothing_brands in brand[1]: which makes no sense since clothing_brands is not even a string.
Fixing that fixes your error;
def findClothing(input_brand):
found = False
for brand in clothing_brands:
if input_brand in brand[1]:
found = True
break
if found:
return brand
else:
return None

Resources