Im able too generate a number properly how I want but I want too make a custom input so the user can generate an exact amount of numbers not just a set amount of numbers.
if menu == "1":
code = input("")
if code == "":
countrycode = input("Please Enter Country Code: ")
areacode = input("Enter area Code: ")
city = (random.randint(200,999))
last = (random.randint(1000,9999))
number = ("+"+countrycode+areacode+str(city)+str(last))
print(number)
To do this, you can use a while True loop that takes in input every single time they want to input a phone number. If they input something that you don't want, break out of the while True loop. Otherwise, you take in the phone number. To hold the set of numbers, just add them to arrays.
Edited off your code:
if menu == "1":
while(True):
code = input("")
if code == "":
countrycode = input("Please Enter Country Code: ")
areacode = input("Enter area Code: ")
city = (random.randint(200,999))
last = (random.randint(1000,9999))
number = ("+"+countrycode+areacode+str(city)+str(last))
print(number)
else:
break
I'm not sure I fully understand your question, but i'll give it a shot:
import random
class Data():
def __init__(self) -> None:
country_code = ""
area_code = ""
city = ""
last = ""
def __str__(self):
return f"+{self.country_code}-{self.area_code}-{self.city}-{self.last}"
def main():
number_of_entries = int(input("How Many Entries: "))
list_of_information = []
for _ in range(0, number_of_entries):
new_data = Data()
new_data.country_code = input("Please Enter Country Code: ")
new_data.area_code = input("Enter area Code: ")
new_data.city = str(random.randint(200,999))
new_data.last = str(random.randint(1000,9999))
list_of_information.append(new_data)
for entry in list_of_information:
print(entry)
if __name__ == '__main__':
main()
Sample:
How Many Entries: 2
Please Enter Country Code: 1
Enter area Code: 604
Please Enter Country Code: 1
Enter area Code: 30
+1-604-394-5276
+1-30-840-8783
Good evening, I have a phonebook code but I am missing the delete feature. I cannot seem to make the delete feature work. All other features like insert, view, add contacts are working already.
I created a phnoebook txt file to store any entries.
phonebook = "d://phonebook.txt"
pbfile = open(phonebook, "a+")
pbfile.close
def show_main_menu():
''' Show main menu for Phone List '''
print("\n *** Phone List Menu ***\n"+
"------------------------------------------\n"+
"Enter 1, 2, 3 or 4:\n"+
"1: Display Your Contacts Records\n" +
"2: Add a New Contact Record\n"+
"3: Search your contacts\n"+
"4: Delete a Contact Record\n"+
"5: Quit\n**********************")
choice = input("Enter your choice: ")
if choice == "1":
pbfile = open(phonebook, "r+")
file_contents = pbfile.read()
if len(file_contents) == 0:
print("Phone List is empty")
else:
print (file_contents)
pbfile.close
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "3":
search_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "4":
delete_contact_record()
user_entry = ("Please Enter to Return to Main Menu ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone List")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
I added the main menu above to show the menu of the phone book, there should be another choice to delete a contact.
The following code is to search for contact. It will show if a contact is already in the phone book but will mention not on record if there is no contact by the name they searched.
def search_contact_record():
''' This function is used to searches a specific contact record '''
contact_search = input("Enter First name to search for contact record: ")
contact_search = contact_search.title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_search in line:
print("You searched for:", end=" ")
print (line)
found=True
break
if found == False:
print("There's no contact Record in Phone List with name = " + contact_search )
The next function is to enter contact and add it to the phonebook txt file created in the beginning.
def enter_contact_record():
''' It collects contact info firstname, last name, email and phone '''
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
email = input('Enter E-mail: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + email + "]\n")
pbfile = open(phonebook, "a")
pbfile.write(contact)
print( "This contact\n " + contact + "has been added successfully!")
#def delete_contact():
show_main_menu()
I got confused on the part how to delete the contact from the txt phonebook. Last delete lines I have trying was the following
def delete_contact_record():
#Initiate a name variable
contact_delete = input('Enter the name of the contact you wish to delete: ').title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_delete in line:
confirm = input('Are you sure you wish to delete '+contact_delete+' y/n?: ')
print(confirm)
if confirm == 'y':
del phonebook[contact_delete]
found = True
if found == False:
print('That contact does not exist! Return to the main menu to enter the contact')
it works up to the line asking for confirmation y/n. But when I enter Y, I get a TypeError: 'str' object does not support item deletion
Thank you.
Your main problem is that your phone book is a flat file. As such, a deletion is "rewrite the entire file, but without the deleted record."
This is, needless to say, very inefficient.
You will also have problems in the future with spurious matches for searches, since contact_search in line is perfectly happy to match parts of names.
Personally, I'd recommend using an SQLite3 database instead of a flat file (SQLite3 support is built in to Python). SQLite3 databases are actually single files, but you can use almost all of the SQL language to perform structured queries, and let it manage the file for you.
If writing SQL is too daunting, the SQLAlchemy Python package can help by making database tables work like Python classes.
I am trying to make a contacts python project but I don't know how to fin da single user. I have tried to find from the file but I am not able to, kindly give the code for that part. If you find any other mistakes kindly resolve that too
This is the code.
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 17:56:45 2020
#author: Teerth Jain
"""
import time
from transpositionDecrypt import decryptMessage as dm
from transpositionEncrypt import encryptMessage as em
key = 8
users = {}
users1 = {}
print("Welcome to Teerth's Contacts Saver and Reader...")
time.sleep(0.5)
r_or_w = input("Do you want or (r)ead or (a)dd or (d)el contacts: ")
if r_or_w == 'r':
what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
#here is the part where you need to give me advice#
if what == 'n':
print("Displaying the whole list...")
q = open('contacts.txt', 'r')
for liness in q:
print(dm(key, liness.strip()))
if r_or_w == 'a':
while True:
addwho = input("Please enter the name: ")
number = input("Please enter the number: ")
file2 = open('contacts.txt', 'r')
y = dm(key, file2.read())
if addwho in y:
print("User in contact list, please try again")
addwho = input("Please enter the name: ")
number = input("Please enter the number: ")
users1.update(addwho = number)
file1 = open('contacts.txt', 'a')
q = f'{addwho} : {number}'
file1.write(em(key, q))
file1.write("\n")
file1.close()
print("Number is ciphered and added.")
again = input("Do you want to add another contact(y, n): ")
if again == 'n':
break
There are no such errors now but if you can modify the code to make it better, kindly do it
Thanks
so, I'm getting a NameError on npc.name(and I imagine it will arise in all subsequent class method-linked variables I'm trying to redefine), also, I have an IndexError arising earlier.
I'll explain in more detail,but first, my code.
This is my full code, beware:
# import pickle
import pickle
npcs_pickle_file = 'NPCatt.pk'
npc_count = 200
class NPC:
def __init__(self, name="", occupation="", weakness="", need="", desire="", enemy="",
rumor="", secret="", passion="", redeeming_quality="",damning_quality="", happy="",
occ_desire="", occ_complication="", pc_opinion="", accomplishment="", magical_gear="",
political_influence="", resource="", intel="", research=""):
# Attributes
self.name = name
self.occupation = occupation
self.weakness = weakness
self.need = need
self.desire = desire
self.enemy = enemy
self.rumor = rumor
self.secret = secret
self.passion = passion
self.redeeming_quality = redeeming_quality
self.damning_quality=damning_quality
self.happy = happy
self.occ_desire = occ_desire
self.occ_complication = occ_complication
self.pc_opinion = pc_opinion
self.accomplishment = accomplishment
self.magical_gear = magical_gear
self.political_influence = political_influence
self.resource = resource
self.intel = intel
self.research = research
def __str__(self):
npc_output = "####NPC SUMMARY####\n"
for att, val in self.__dict__.items():
if val:
npc_output += (f"{att} = {val}\n")
return npc_output
# open a pickle file
# load your data back to memory when you need it
try:
with open(npcs_pickle_file, 'rb') as fi:
npcs = pickle.load(fi)
except FileNotFoundError as fne:
#file doesnt exist prob first time running so create a dict with the 170 npc id's
npcs = {id: None for id in range(npc_count)}
#select an NPC to modify / create
npc_id = None
while not npc_id:
try:
npc_id = int(input(f"Enter the id number of the NPC you wish to modify: "))
except ValueError as ve:
print("You must provide a numerical id")
if npc_id < 0 or npc_id >= npc_count:
npc_id = None
print(f"you must provide a value between 0 and {npc_count}")
if npcs[npc_id]:
npc = npcs[npc_id]
print(npc)
modify = input("This NPC already exists, do you want to continue and change them? (y/n): ")
if modify.lower() == "y":
name = input("Enter name of NPC: ")
occupation = input("Enter NPC occupation: ")
weakness= input("Enter Weakness: ")
need= input("Enter Need: ")
desire= input("Enter Desire: ")
enemy= input("Enter Enemy: ")
rumor= input("Enter Rumor: ")
secret= input("Enter Secret: ")
passion= input("Enter Passion: ")
redeeming_quality=input("Enter Redeeming Quality: ")
damning_quality=input("Enter Damning Quality: ")
happy= input("Enter, is this NPC happy?: ")
occ_desire= input("Enter an Occupational Desire: ")
occ_complication= input("Enter an Occupational Complication: ")
pc_opinion= input("Enter this NPC's disposition toward the PCs: ")
accomplishment= input("Enter an Accomplishment: ")
magical_gear= input("Enter Magical Gear: ")
political_influence=input("Enter Political Influence: ")
resource= input("Enter Resource Level: ")
intel= input("Enter Intel Tier: ")
research= input("Enter Research: ")
npc.name = name
npc.occupation = occupation
npc.weakness = weakness
npc.need = need
npc.desire= desire
npc.enemy= enemy
npc.rumor= rumor
npc.secret= secret
npc.passion= passion
npc.redeeming_quality= redeeming_quality
npc.damning_quality= damning_quality
npc.happy= happy
npc.occ_desire=occ_desire
npc.occ_complication=occ_complication
npc.pc_opinion=pc_opinion
npc.accomplishment=accomplishment
npc.magical_gear=magical_gear
npc.political_influence=political_influence
npc.resource=resource
npc.intel=intel
npc.research=research
else:
npcs[npc_id] = NPC(name=npc.name, occupation=npc.occupation,weakness=npc.weakness,need=npc.need,desire=npc.desire,\
enemy=npc.enemy,rumor=npc.rumor,secret=npc.secret,passion=npc.passion,redeeming_quality=npc.redeeming_quality,\
damning_quality=npc.damning_quality,happy=npc.happy,occ_desire=npc.occ_desire,\
occ_complication=npc.occ_complication\
,pc_opinion=npc.pc_opinion,accomplishment=npc.accomplishment,\
magical_gear=npc.magical_gear,political_influence=npc.political_influence,resource=npc.resource,\
intel=npc.intel,research=npc.research)
else:
name = input("Enter name of NPC: ")
occupation = input("Enter NPC occupation: ")
weakness= input("Enter Weakness: ")
need= input("Enter Need: ")
desire= input("Enter Desire: ")
enemy= input("Enter Enemy: ")
rumor= input("Enter Rumor: ")
secret= input("Enter Secret: ")
passion= input("Enter Passion: ")
redeeming_quality=input("Enter Redeeming Quality: ")
damning_quality=input("Enter Damning Quality: ")
happy= input("Enter, is this NPC happy?: ")
occ_desire= input("Enter an Occupational Desire: ")
occ_complication= input("Enter an Occupational Complication: ")
pc_opinion= input("Enter this NPC's disposition toward the PCs: ")
accomplishment= input("Enter an Accomplishment: ")
magical_gear= input("Enter Magical Gear: ")
political_influence=input("Enter Political Influence: ")
resource= input("Enter Resource Level: ")
intel= input("Enter Intel Tier: ")
research= input("Enter Research: ")
npc.name = name
npc.occupation = occupation
npc.weakness = weakness
npc.need = need
npc.desire= desire
npc.enemy= enemy
npc.rumor= rumor
npc.secret= secret
npc.passion= passion
npc.redeeming_quality= redeeming_quality
npc.damning_quality= damning_quality
npc.happy= happy
npc.occ_desire=occ_desire
npc.occ_complication=occ_complication
npc.pc_opinion=pc_opinion
npc.accomplishment=accomplishment
npc.magical_gear=magical_gear
npc.political_influence=political_influence
npc.resource=resource
npc.intel=intel
npc.research=research
with open(npcs_pickle_file, 'wb') as fi:
# dump your data into the file
pickle.dump(npcs, fi)
I'm a noob so the code structure was provided as an answer on my only other question so far on the site. I've expanded it for my purposes.
The thing is, the NPC indexed as [1], has been stored perfectly, shows up as needed, and is modifiable.
But when defining new NPCs, I get first an IndexError for new Indexable NPCs, which I caught with a
try: #the code for when the NPC has been previously defined
except IndexError:#the code on the last else block, for new indexes
in order to check whether the rest of the code worked,
and a NameError arises on the last else block where I define each attribute as
self.att=att
now, my best guess is that it has to do with local vs global variable definitions, but I have no idea how to solve either error.
Thank you if you read all the way through, and I'm sorry.
Please help, if you can and want to.
Your IndexError issue comes from unpickling a file created by the previous version of your script. If this file contains valuable data, just rename it for the moment, and once you'll get you script working and stable enough, it will be time to write a migration script to get your old data back. Else, well, just ditch it xD
wrt/ the NameError, it's in the last else block: you are trying to set attributes on a npc variable that is indeed not defined at this point - it's only defined in the if block:
if npcs[npc_id]:
npc = npcs[npc_id]
# way too much code here
else:
# repeated code here
# and here's the issue:
npc.something = something
You already noticed that "mashing together pieces of code without understanding them doesn't always work", which is a good start (at least you're aware of it, so there's still hope xD), now here's another enlightenment for you: "trying to understand messy code is hard". That's why good code structure is important. Also, short functions that only (or mostly) depend on their arguments are easier to understand (and test !) than long scripts with lots of conditionals and code blocks that depends on some variable being (or not) defined some 20+ lines away.
I usually don't do this, but it seems that in this case, you may benefit from seeing what a decently structured code looks like. It's far from perfect and could benefit from some improvements (like, when editing an existing npc, letting the user specify which attributes he wants to change instead of asking them to retype everything) but well, that's your job, not mine ;-)
import pickle
# coding conventions: pseudo-constants should be ALL_UPPER
NPCS_PICKLE_FILE = 'NPCatt.pk'
NPC_COUNT = 200
# coding convention: class names should be CamelCase
class Npc:
def __init__(self, name="", occupation="", weakness="", need="", desire="", enemy="",
rumor="", secret="", passion="", redeeming_quality="",damning_quality="", happy="",
occ_desire="", occ_complication="", pc_opinion="", accomplishment="", magical_gear="",
political_influence="", resource="", intel="", research=""):
# Attributes
self.name = name
self.occupation = occupation
self.weakness = weakness
self.need = need
self.desire = desire
self.enemy = enemy
self.rumor = rumor
self.secret = secret
self.passion = passion
self.redeeming_quality = redeeming_quality
self.damning_quality = damning_quality
self.happy = happy
self.occ_desire = occ_desire
self.occ_complication = occ_complication
self.pc_opinion = pc_opinion
self.accomplishment = accomplishment
self.magical_gear = magical_gear
self.political_influence = political_influence
self.resource = resource
self.intel = intel
self.research = research
def update(self, **values):
for key, val in values.items():
# make sure we're only accepted known attributes
if not hasattr(self, key):
raise AttributeError("Npc object has no attribute '{}'".format(key))
setattr(self, key, val)
def __str__(self):
# in Python, string concatenation is better done by
# building a list and joining it afterward
npc_output = ["####NPC SUMMARY####"]
for att, val in self.__dict__.items():
if val:
npc_output.append(f"{att} = {val}")
npc_output.append("") # so we have a last newline
return "\n".join(npc_output)
class InvalidDataFile(ValueError):
pass
def load_npcs_from_file():
with open(NPCS_PICKLE_FILE, 'rb') as fi:
try:
npcs = pickle.load(fi)
except EOFError as e:
raise InvalidDataFile(
"looks like {} is empy - expected a dict, got {}".format(NPCS_PICKLE_FILE, e)
)
# make sure we don't have incorrect data from
# the previous version where what was pickled was a list
if not isinstance(npcs, dict):
raise InvalidDataFile(
"looks like {} is obsolete or corrupted - expected a dict, got {}".format(NPCS_PICKLE_FILE, ncps)
)
# make sure we ALWAYS have `NPC_COUNT` npcs whatever
# (ie: in case the pickle didn't have as many entries as expected)
missing = NPC_COUNT - len(npcs)
if missing > 0:
for id in range(NPC_COUNT):
ncps.setdefault(id, None)
return npcs
def init_npcs():
return {id: None for id in range(NPC_COUNT)}
def load_npcs():
try:
return load_npcs_from_file()
except (FileNotFoundError, InvalidDataFile) as e:
# so you know what's happening...
print("got {} when trying to load npcs from file - creating a new dataset".format(e))
return init_npcs()
def save_npcs(npcs):
with open(NPCS_PICKLE_FILE, 'wb') as fi:
# dump your data into the file
pickle.dump(npcs, fi)
def get_npc_values():
# factor out common stuff
# XXX you definitly want to validate user inputs
values = {}
values["name"] = input("Enter name of NPC: ")
values["occupation"] = input("Enter NPC occupation: ")
values["weakness"] = input("Enter Weakness: ")
values["need"] = input("Enter Need: ")
values["desire"] = input("Enter Desire: ")
values["enemy"] = input("Enter Enemy: ")
values["rumor"] = input("Enter Rumor: ")
values["secret"] = input("Enter Secret: ")
values["passion"] = input("Enter Passion: ")
values["redeeming_quality"] = input("Enter Redeeming Quality: ")
values["damning_quality"] = input("Enter Damning Quality: ")
values["happy"] = input("Enter, is this NPC happy?: ")
values["occ_desire"] = input("Enter an Occupational Desire: ")
values["occ_complication"] = input("Enter an Occupational Complication: ")
values["pc_opinion"] = input("Enter this NPC's disposition toward the PCs: ")
values["accomplishment"] = input("Enter an Accomplishment: ")
values["magical_gear"] = input("Enter Magical Gear: ")
values["political_influence"] = input("Enter Political Influence: ")
values["resource"] = input("Enter Resource Level: ")
values["intel"] = input("Enter Intel Tier: ")
values["research"] = input("Enter Research: ")
return values
def update_npc(npc):
new_values = get_npc_values()
npc.update(**new_values)
def create_npc():
values = get_npc_values()
return Npc(**values)
def get_npc_id():
#select an NPC to modify / create
npc_id = None
while npc_id is None:
try:
npc_id = int(input(f"Enter the id number of the NPC you wish to modify: "))
except ValueError as ve:
print("You must provide a numerical id")
if npc_id < 0 or npc_id >= NPC_COUNT:
npc_id = None
print(f"you must provide a value between 0 and {NPC_COUNT}")
return npc_id
def edit_npc(npcs):
npc_id = get_npc_id()
# this should be safe now... theoretically at least
npc = npcs[npc_id]
if npc is None:
ok = input("This NPC doesn't exist yet, do you want to create it (y/n): ")
if ok.strip().lower() == 'y':
npcs[npc_id] = create_npc()
# let the caller know something was changed
return True
else:
ok = input("This NPC already exists, do you want to continue and change them? (y/n): ")
if ok.strip().lower() == "y":
update_npc(npc)
# let the caller know something was changed
return True
# let the caller know nothing was changed
return False
def show_npcs(npcs):
for id, npc in npcs.items():
print("{} : {}".format(id, npc))
print("") # add a blank line
def get_next_action():
while True:
print("what do you want to do ?")
print("S - show existing npcs")
print("E - edit a npc")
print("Q - quit")
action = input(">> ").strip().upper()
if action not in "SEQ":
print("sorry, I don't undertand '{}'".format(action))
return action
def main():
npcs = load_npcs()
while True:
nb_valids = len([_ for _ in npcs.values() if _])
print("we have {} valid npcs".format(nb_valids))
action = get_next_action()
if action == "Q":
break
elif action == "E":
if edit_npc(npcs):
print("saving data")
save_npcs(npcs)
elif action == "S":
show_npcs(npcs)
if __name__ == "__main__":
main()
Using python I am trying to make it where the books in a text file display and the user can select a book and a quantity and do this in a loop. As they do this it is supposed to save it to a text file as a receipt and print it out when the user is done making their selections. This is what I've been able to accomplish so far.
cusName = input("What is your name?")
def main():
def menu():
print("Here is a list of items that we have:")
books_file= open("Books.txt","r")
lines = books_file.readlines()
aryBooks = []
for line in lines:
print(line)
bookChoice = input("Which book would you like?")
bookQty = input("You chose", bookChoice , "How many would you like?")
print ("Qty:", bookQty)
print ("Item:", bookChoice)
price = print ("Price:", book[2])
print ("SubTotal:", price * bookQty)
repeat = input("Would you like another item? Y or N")
receipt_file= open("receipt.txt","w")
lines = receipt_file.writelines()
for i in range(0,len(aryBooks)):
print(i + 1, aryBooks[i])
Try the code below:
def menu():
# Main loop for shopping
cart = {}
# Read books here
books = read_books()
while True:
# Loop until user does not want to shop any longer
print("Here is a list of items that we have:\n")
for book_num, (book_name, book_price) in books.items():
print(f'#{book_num}: {book_name} -- ${book_price}')
bookChoice = input("Which book would you like? (Please enter a number)\n")
# Make sure user enters the right number
try:
price = books[bookChoice][1]
except:
print('Sorry you chose the wrong number')
print()
continue
bookQty = int(input(f"You chose {books[bookChoice][0]}. How many would you like?\n"))
subtotal = price * bookQty
cart[books[bookChoice][0]] = (bookQty, subtotal)
print (f"Qty: {bookQty}")
print (f"Item: {books[bookChoice][0]}")
print (f"Price: {price}")
print (f"SubTotal: {subtotal}")
repeat = input("Would you like another item? Y or N\n")
# End loop if answer was No
if repeat.lower() == 'n' or repeat.lower == "no":
print(f'Your total was: {sum([y for x, y in cart.values()])}')
generate_receipt('receipt.txt', books, cart)
print('Have a good day!\n')
break
else:
print('Here is what you have thus far:')
for name, (qty, sub) in cart.items():
print(f'Name: {name} ; Qty: {qty} ; Subtotal: {sub}')
print()
def generate_receipt(path_to_receipt, books, cart):
# Generate receipt based on shopping cart
with open(path_to_receipt, 'a') as receipt_file:
for name, (qty, subtotal) in cart.items():
receipt_file.write(f'Qty: {qty} ; Item: {name}; Total: {sum([y for x, y in cart.values()])}; Subtotal: {subtotal}\n')
def main():
# Main loop that starts the shopping
cusName = input("What is your name?\n")
print(f'Hi {cusName}. Welcome to the bookstore!')
menu()
def read_books(path_to_books="Books.txt"):
# Read in the books from the file
with open(path_to_books, 'r') as f:
books = f.readlines()
books = [book.strip().split(',') for book in books]
books = {book_num: (book_name, int(book_price)) for book_num, book_name, book_price in books}
return books
if __name__ == '__main__':
main()
The output file might not be what you want but that can be fixed really easily.
My Books.txt is as follows:
15,Harry Potter,20
2,LOTR,25