Trying to create program to answer this question:
[ ] The records list contains information about some company's employees
each of the elements in records is a list containing the name and ID of an employee.
Write a program that prompts the user for a name and return the ID of the employee if a record is found
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
This is my code, so far:
ui = input('Enter employee name: ')
for row in records:
if row[0] in ui:
print(row[1])
else:
print('Employee not found!')
ui = input('Enter employee name: ')
I cannot seem to find a way to check if 'ui' is in the records list.
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
user_name = 'colette' # User input
for i in range(0,len(records)):
# Here I make User name and Name in Recored in lower case so it can match perfectly
if user_name.lower() in records[i][0].lower():
print(records[i])
else:
print("employee not found")
Associate the else block with the for loop instead of the if statement
ui = input('Enter employee name: ')
for row in records:
if row[0] == ui:
print(row[1])
break
else:
print('Employee not found!')
But, if you convert the nested list to a dict, it would be much easier to get the 'id'
ui = input('Enter employee name: ')
d = dict(records)
print(d.get(ui, 'Employee not found!'))
You can use list comprehension to do it -
[i for i in records if ui in i]
This will give you a list of list of employee you are trying to find else empty list.
For ex-
ui = 'Colette'
O/P -
[['Colette', 22347]]
You could do something like -
ui = input('Enter employee name: ')
found = [i for i in records if ui in i]
if found:
for emp in found:
print(emp[1])
else:
print("Employee not found")
This should take care of it, Do keep in mind when comparing two strings, python doesn't automatically convert uppercase to lowercase so its important if you intend to compare a string that you convert both the string in either lower or uppercase
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
ui = str.lower(input('Enter employee name: '))
names_to_compare=[t[0].lower() for t in records]
if ui in names_to_compare:
print(records[names_to_compare.index(ui)][1])
else:
print("Employee not in records")
Related
I'm trying to delete a specific input of user using del function but it deletes the whole key values below it
for account3 in accounts:
print("\t ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
userinput = input('Account Name you want to delete: ')
for account4 in accounts:
if userinput == account4["Name"]:
userinput = input('Re-enter name to confirm: ')
for account5 in accounts:
if userinput == account5["Name"]:
del account5["Name"], account5["Username"], account5["Password"]
print('Deleted Successfully!')
menu()
break
After the user confirms the deletion, it deletes all values in the dictionary and gives a key error: "name". Is there any way to delete only the information given by the user?
Setting the values to None is what you want instead of deleting the entries.
Replace the del line with this.
account5["Name"], account5["Username"], account5["Password"] = None, None, None
To avoid having to loop through the list multiple times to find the matching account, I suggest building a dict that maps the name to each account, and using accounts.remove() to remove the account.
accounts_by_name = {account["Name"]: account for account in accounts}
for account in accounts:
print("\t ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
name = input("Account name you want to delete: ")
if name not in accounts_by_name:
continue
if input("Re-enter name to confirm: ") != name:
continue
accounts.remove(accounts_by_name[name])
menu()
break
I am completing the 30 day hackerrank challenge. This is the question: Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead. I've managed to pass all the test cases except 1, I got a runtime error when the numberOfEntries was 1000. How do I fix this?
numberOfEntries = int(input())
phoneBook = dict()
for i in range(0,numberOfEntries):
entry = input()
temp = entry.split(" ")
phoneBook[temp[0]] = int(temp[1])
for index, item in enumerate(phoneBook):
query = input()
if index == numberOfEntries:
break
if query in phoneBook.keys():
print(f"{query}={phoneBook[query]}")
else:
print("Not found")
Thank you for everyone's input. Turns out the only thing I needed to do was:
numberOfEntries = int(input())
phoneBook = dict()
for i in range(0,numberOfEntries):
entry = input()
temp = entry.split(" ")
phoneBook[temp[0]] = int(temp[1])
for index, item in enumerate(phoneBook):
try:
query = input()
if index == numberOfEntries:
break
if query in phoneBook.keys():
print(f"{query}={phoneBook[query]}")
else:
print("Not found")
except:
break
I'll definitely edit the code to make sure it accepts operators and 0's too, so thank you!
The user needs to input the table number (Tables are numbered from 0 to 19). If the table is not available (reserved), inform the user that the selected table is not available. If the table is available, then ask for the name (name is a single word, no space) and mark the table as reserved. Now I need to keep two arrays (parallel arrays!), both are size 20, one of type boolean (true/false -- reserved/available) and the other one of type string (name on reservation if reserved, blank otherwise)
tableNum = []
def reserve():
global table
global name
global tableNum
avaible = False
tablenum = int(input("Enter a number: "))
if not tablenum in tableNum:
name = input("Table is avaiable, please enter your name: ")
else:
print("Table is unavaiable")
while(True):
print("1- Reserve a Table")
print("2- Clear Reservation")
print("3- Report")
print("0- Exit")
choice = int(input("Choose a option "))
if choice == 1:
reserve()
You could do it without keeping a list of all the tables. Append reservations as a key, value pair to a dictionary. You can then check if the input matches a key in the reservation dictionary. You can then use the reverse to remove a reservation.
reservationDictionary ={}
def reserve():
global reservationDictionary
tablechoice = int(input('Tables are numbered 0-19, Choose a table number'))
if tablechoice not in reservationDictionary.keys():
name = input("Table is available, enter your Name: ")
reservationDictionary[tablechoice] = name
else:
print("Table is unavailable")
Update to remove a booking:
def removeReservation():
global reservationDictionary
removetable = int(input('Choose table number to remove reservation for that table'))
if removetable not in reservationDictionary.keys():
print("This table doesn't have a reservation")
else:
del reservationDictionary[removetable]
print("Reservations for table {} has been deleted".format(removetable))
im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.
When the user enters the first name and if it is blank or has digit or alphanumeric or has non ascii chars I am not going to insert it into database.
With this code below it does not accept valid input, it works only if I use len and isDigit those 2 conditions.
while (len(f_name) == 0 or f_name.isdigit()
or
f_name.encode('ascii',errors='ignore') or f_name.isalnum()):
Create new user: Y/N ?y
Enter first name: ui
First name cannot be empty or have numeric values
Can someone please explain how to fix this issue? Thanks for your time. Rest of the code is below:
import sqlite3
#connect a built in function to connect or create db
conn=sqlite3.connect('phonebook.db')
#Create a cursor function which allows us to do sql operations
crsr=conn.cursor()
#This function to check if table exists
def create_Table():
#Check if the table exists or not
crsr.execute("SELECT name FROM sqlite_master WHERE name='phonebook'")
tableSize=len(crsr.fetchall())#will be greater than 0 if table exists
if tableSize>0:
print()
else:
#create the table
crsr.execute(""" Create Table phonebook(
FirstName text NOT NULL,
LastName text,
Phone text PRIMARY KEY NOT NULL)
""")
#check if table got created or not
crsr.execute("SELECT name FROM sqlite_master WHERE name='phonebook'")
tableSize = len(crsr.fetchall()) # will be greater than 0 if table exists
if tableSize > 0:
print('Table was created successfully')
#This function will create new users and insert in DB
def create_User():
try:
while True:
rsp = input('Create new user: Y/N ?')
if rsp == 'y':
f_name = input('Enter first name: ')
# First name cannot be empty or have numeric values
while (len(f_name) == 0 or f_name.isdigit() or f_name.encode('ascii',errors='ignore') or f_name.isalnum()):
print('First name cannot be empty or have numeric values')
f_name = input('Enter first name: ')
l_name = input('Enter last name: ')
phone = input('Enter phone number: ')
crsr.execute("INSERT INTO phonebook VALUES (:FirstName, :LastName, :Phone)",
{'FirstName': f_name, 'LastName': l_name, 'Phone': phone})
conn.commit()
if rsp == 'n':
break
except:
print('UNIQUE constraint failed: phone number already exists')
Use isalpha to ensure the string is only letters:
f_name = input('Enter first name: ')
if f_name and f_name.isalpha():
# your ACCEPTED logic here
Futhermore, if you need to check that those letters are ASCII, you can sweetly compare their encoded length to themselves:
f_name = input('Enter first name: ')
if f_name and f_name.isalpha() and len(f_name) == len(f_name.encode()):
# your ACCEPTED logic here
EDIT Added empty string check (i.e. if f_name)
If you are comfortable with regular expressions, you can test for the conditions "must not be empty" and "must not contain digits" in the following way:
import re
# match one or more characters that range from a to z or A to Z
username_check = re.compile(r'[a-zA-Z]+')
...
while True:
if rsp == 'y':
f_name = input('Enter first name: ')
while not username_check.fullmatch(f_name):
print('First name cannot be empty or have numeric values')
f_name = input('Enter first name: ')
The nice thing about regular expressions is that you can extend the current minimal solution quite flexibly to test for very specific patterns as well:
import re
# allow unicode word characters
allowed = re.compile(r'\w+')
# numbers are still not allowed
forbidden = re.compile(r'\d')
while True:
f_name = input('Enter first name: ')
while not (allowed.fullmatch(f_name) and not forbidden.search(f_name)):
print('First name cannot be empty or have numeric values')
f_name = input('Enter first name: ')