Currently I'm doing my first project which consists on a program for restaurants.
To log in as a waiter/tres you insert your name and is added to a TXT file.
My problem is that in the code when I print the TXT file to see the users that signed in it won't show the updated list if not the original list.
snames = list()
f_n = (open('names.txt')).read()
print("Welcome to NAME.app")
try:
while True:
name = input("Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:")
if name.lower() == "add":
n_input = input("Name:")
with open('names.txt', 'a') as f:
f.write(n_input + '\n')
continue
elif name.lower() == "list":
print(f_n.split())
elif name == snames:
print("Logged as", name)#doubtful line. print name of list.
elif name == "exit":
exit()
except:
print("Invalid input")
In the second ELIF is what I wrote to see saved names(users).
But as I said prints the TXT file without including what I added in the first IF.
This might help.
OUTPUT
Welcome to NAME.app
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:add
Name:Python
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:list
['Ale', 'Sarah', 'Annette', 'Dan']
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:
Appreciate recommendations and solutions.
thank you very much.
In the first line you read all the names, only after that you added more names, so the f_n variable doesn't get updated.
Change the "list" option to this
elif name.lower() == "list":
with open('names.txt') as f:
print(f.read().splitlines())
This will make sure to read the updated list each time you choose this option
Related
im trying to code a simple contact book with just names and phone numbers. I want it to have the options add,remove,search and exit obviously. In my remove and search option i got one problem: For example if the use adds a new name to the contact book for example "Alex Balex" and wants to remove it or search it after he needs to type Alex Balex but i want the program to find and delete Alex out of the list if i search for "Alex Bal" aswell. That was my attempt but i cant find a solution:
import pickle
import sys
while True:
option = int(input(("You got 3 options 1=add 2=remove 3=search 4=exit and save. Please enter what you want to do: ")))
if option == 1:
names = []
names = pickle.load(open("names.dat", "rb"))
new_entry, new_number = str(input("Enter a new name which you want to be added to the CB in this format name:phone_number\nINPUT: ")).split(":")
new_user = "Name: " + new_entry + " Number: " + new_number
names.append(new_user)
pickle.dump(names, open("names.dat", "wb"))
elif option == 2:
names = []
names = pickle.load(open("names.dat", "rb"))
print(names)
new_removal = str(input("Enter what you want to remove: "))
for element in names:
if new_removal in element:
names.remove(names[names.index(element)])
pickle.dump(names, open("names.dat", "wb"))
elif option == 4:
sys.exit()
elif option == 3:
names = []
names = pickle.load(open("names.dat", "rb"))
print(names)
new_search = str(input("Search either a name or a number: "))
for element in names:
if new_search in element:
new_search = names[names.index(element)]
print(new_search)
pickle.dump(names, open("names.dat", "wb"))
A simple solution to your problem is to find the first name with the prefix the user entered, and then remove that:
elif option == 2:
new_removal = str(input("Enter what you want to remove: "))
i_remove = -1
for i, name in enumerate(names):
if name.lower()[0:len(new_removal)] == new_removal.lower():
i_remove = i
break
if i_remove != -1:
names.remove(i_remove)
else:
print(f"Name not found: {new_removal}", file=sys.stderr)
One question you'll need to consider though is what to do if multiple names start with the same prefix.
For example, what if a user's contact list contains Alex Balex, and Alex Ball, and the user asks to remove Alex Bal?
The simplest solution here would be to simply not remove anything since the specific name of the contact cannot be deduced - but another option might be instead to prompt the user with the list of contacts with that prefix and ask them to choose which one they want to remove.
I leave this part to you - good luck!
I am practicing python and doing an exercise where I have to ask for input of different information from patients of a hospital (name, last name, etc) this information has to be saved in a different json file. I managed to do it however I also have to make it so, with an input, I can remove/edit a specific patient from the dictionary (along with all of their info) while keeping the others intact.
I was thinking that maybe I could assign a number to every patient that's added, so this patient can be tracked with the number, however I'm not sure how to code that. I did however made a function to clear everything from the json file, but it has to remove/edit someone specific, not everyone.
My code so far is:
import json
def read_file(file_name):
obj_arch = open(file_name, 'rt', encoding='utf-8')
str_contenido = obj_arch.read()
res = json.loads(str_contenido)
obj_arch.close()
return res
def save_file(file_name, lista):
obj_arch = open(file_name, 'wt', encoding='utf-8')
str_content_to_save = json.dumps(lista)
print(str_content_to_save)
obj_arch.write(str_content_to_save)
obj_arch.close()
opcion = int(input("choose an option: 1 - read. 2 - save"))
if opcion == 1:
lista = read_file('prueba_json.json')
print("Full list:")
print(lista)
else:
lista = read_file('prueba_json.json')
while True:
print("--- PATIENT INFO ---")
Name = input("Input name: ")
Lastname = input("Input lastname: ")
DateB= input("Input date of birht: ")
repeat = input("Do you want to add more info?: ")
clean_file = input("Clean everything from the json file? (yes/no): ")
lista.append({
"Name": Name,
"Lastname": Lastname,
"Date of Birth": DateB
})
if repeat == 'no' or repeat == 'NO':
break
save_file('prueba_json.json',lista)
With this I was able to sabe the patients info in the json file, but how can I write another input like "Insert number of patient to remove or delete" to do that?
In order to clean the whole json file I've done it with this:
def clean_json():
with open('prueba_json.json', 'w') as arc:
arc.writelines(["[{}]"])
if clean_file == "yes" or clean_file == "YES":
clean_json()
Maybe I could adapt some of this to remove or delete someone instead of the whole file?
in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')
I am very new to sw coding needing some help. Thank You!
I have a script that scan a path for .py files and display it it in menu format using enumerates
Ask user to select file/files they want to run and put them in a list
And start ran those file from this list one by one
My issue is that it only ran the the fist selected file from the user selected list. Here is my simple code.
import os
import sys
choice_1 = ''
run_list = []
while choice_1 != 'q':
print("\nPlease select desire test case: ")
items = os.listdir("C:/Users/tonp\PycharmProjects/untitled1")
fileList = [name for name in items if name.endswith(".py")]
for cnt, fileName in enumerate(fileList, 0):
sys.stdout.write("[%d] %s\n\r" % (cnt, fileName))
choice = int(input("Select from [1-%s]: " % cnt))
choice_1 = input("Press any key to add more case or q to start running testsuite ")
run_list.append(fileList[choice])
print("These are the case/s you have selected so far :")
print(run_list)
selected_files = run_list
for x in run_list:
exec(open(c).read())
You may need to use importlib.
Check this link for an answer that might help you in this direction:
Exit an imported module without exiting the main program - Python
To allow the user to exit as needed you can do something like this inside the while True:
sys.stdout.write('Type file name (Enter to exit): ')
try:
sys.stdout.flush()
filename = sys.stdin.readline().strip()
if filename == '':
print('Exiting...')
break()
except:
exit()
I am new to Python. I am trying to run the following code. But every time I try to run it, the IDE says that the break is outside the loop
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Can you please help me?
Thanks
You use break when you want to break free from a loop, to exit the loop, to jump to the nearest code after the loop.
Your code doesn't contain a loop, so nothing to break free from, hence the error.
I think you meant exit() instead of break
You use "break" just inside the loop ("for" or "while"), you are trying use brake inside the "if"
How about this:
if name != '':
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Your break statement is not in a loop, it's just inside an if statement.
But maybe you want to do something like the following.
If you want to let the user enter an random number of names and print the names out, when the user entered nothing, you can do the following:
# Here we declare the list in which we want to save the names
catnames = []
# start endless loop
while True:
# get the input (choose the line which fits your Python version)
# comment out the other or delete it
name = input("Enter the name of a cat\n") # input is for Python 3
# name = raw_input("Enter the name of a cat\n") # raw_input is for Python 2
# break loop if name is a empty string
if name == '':
break
# append name to the list catnames
catnames.append(name)
print("The cat names are :")
# print the names
for name in catnames:
print(name)
What you are looking for is exit().
However, your code has also other problems, here is a piece of code that does what you probably want (when prompted, enter the names separated by spaces, like: Cat1 Cat2):
name = raw_input("Enter the name of the cats: ")
if len(name) == 0:
exit()
print("\nThe cat Names are:")
for c_name in name.split():
print(c_name)
If this is the entirety of your code, then it's telling you exactly what the problem is:
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
You have a break statement in the code that's not contained inside a loop. What do you expect the code above to do?