I'm creating a address book program, and need to have a dictionary that I can add too, edit, and delete, as well as pickle. What would be the best way to create it so it is accessible by all the functions? I currently have the dictionary in the addon function but wouldn't it reset if I were to call the dictionary to another function?
My code so far (not including the menuModule)
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def appendDictionary():
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
listX = [personFirstName, personEmail, personStreetAddress, personCityState, personPhone]
addressBook = {personLastName: listX}
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
Try using lists. One list for each of the variables because if you try to store them as a tuple and then add them into a master list you will not be able to or it will be hard to charge them and edit them. Here is an example of storing the data:
nameList.extend(john)
emailList.extend(john#gmail.com.uk)
john_index = len(nameList)
Give each person an index to help you file their information so if our list looked like [jane#live.com, sam#wenston.com, john#gmail.com.uk] johns data is going to be the last in the list because we just entered it in position 3 on the list and the length function returns 3 so you know where johns data is stored and if you were to add more data it would stack up accourdingly.
here is an example of getting it back out of the list and editing it:
print nameList[john_index]
print emailList[john_index]
emailList[john_index] = new_value
I hope you understand :)
Related
I am teaching myself Python. For practice I made a little mad lib game for my daughter. The problem, I want to add a "to continue press enter or type quit to exit" after line 3. I know I'm obviously doing it wrong, but I've tried conditional, flags and breaks with no luck.
#Prompt
greeting = input("Hello what is your name? ")
greeting += input(f" OK {greeting} lets wright a story together. Lets get started" )
#listing of directions
while True:
q_1 =input("please type a plural noun : ")
q_2 = input("please type an adjective: ")
q_3 =input ("please type plural noun, animal: ")
q_4 =input("Please enter an plural noun: ")
q_5 = input("Please enter an adjective: ")
q_6 = input("Please enter a color: ")
q_7 = input("Please enter an adjective: ")
q_8 = input("Please enter noun: ")
q_9 = input("Please enter plural noun: ")
q_10 =input("Please enter an adjective ")
q_11 = input("Please enter a verb: ")
q_12 = input("Please enter plural noun ")
q_13 = input("Please enter a verb-ed: ")
q_14 = input("Please enter a verb: ")
q_15 = input("Please enter noun: ")
q_16 = input("Please enter a adjective: ")
break
print("Ok here's your story")
# output with data from input
story = f"""
Unicorns aren't like other {q_1}; they're {q_2}. They look like
{q_3}, with {q_4} for feet and a {q_5} mane of hair. But Unicorns
are {q_6} and have a {q_7} {q_8} on their heads. Some {q_9} don't
believe Unicorns are {q_10} but I believe in them. I would love to
{q_11} a Unicorn faraway {q_12}. One thing I've always {q_13} about
is whether Unicorns {q_14} rainbows, or is their {q_15} {q_16}
like any other animals?
"""
print(story)
To answer your question, I've suggest something simple like this.
#Prompt
greeting = input("Hello what is your name?\n")
print(f"OK {greeting} lets wright a story together. Lets get started")
play = input('to continue press enter or type quit to exit\n')
if play == 'quit':
quit()
# Rest of your code stays the same
I'll mention also, because you said you are doing this for practice, that the way you are asking for inputs is a little bit rough.
In my example above I added a \n character. This will stop you needing to use all those spaces by putting the input response on a new line.
When I run the program it asks for my input multiple times even after I've entered it once already.
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
Asks the user to input a name which is the key to a value, which it returns
for i in Peeps:
if i == input("Type in a name: "):
print("The amount", [i], "owes is:", "$" + str(Peeps[i]))
break
else:
print("Sorry that name does not exist, please enter a new name.")
You need to ask the user input first instead of comparing the user input directly to the key.
You do not want to do it like that. Take a look at the following instead:
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
name = input("Type in a name: ")
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
You do not have to loop through your dict and check the user input against each value individually (plus you are forcing the user to update\re-enter his input continuously).
Just receive it once and process it.
If you want to keep the loop running to allow for multiple queries, use while like so:
Peeps = {"Juan": 244, "Jayne": 433, "Susan": 751}
name = input("Type in a name or leave blank to exit: ")
while name:
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
name = input("Type in a name or leave blank to exit: ")
If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook
Just started venturing into arrays using python 2.7.5. My objective is to ask the user for input and store the input in multiple arrays.
So far this is what I have, as far as storing multiple arrays with input. I run into an error when trying to print the input at the end.
Here is the code I have so far.
# want user to enter a list of employee names, error occurs when trying to recall user entry
emp_name = [0]
emp_name = raw_input("please enter employee name")
while emp_name !="neg":
emp_name = raw_input("please enter employee name,enter neg to exit")
print "employee 2 is:", emp_name[1] #I want the 2nd name entered to appear
Then you are going to want to:
Change the names of your variables so that you don't have the list be the same name as the input.
Append each name you get to the list.
This should be what you want:
employees = []
name = raw_input("Please enter an employee name: ")
while name != "neg":
# Append the previous name.
employees.append(name)
# Get a new name.
name = raw_input("Please enter an employee name or 'neg' to exit: ")
# You need a try/except here in case there is no second employee.
# This can happen if the user types in "neg" to begin with or only 1 name.
try:
print "Employee 2 is: ", employees[1]
except IndexError:
print None
Also, I slightly changed your input prompts to make them cleaner and more user-friendly.
Below is a sample of the script in action:
Please enter an employee name: Bob
Please enter an employee name or 'neg' to exit: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: Joe
And here is one without a second employee:
Please enter an employee name: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: None
Your first line declares emp_name as an array.
Your second line raw_input("please enter employee name") re-assigns it as a string.
So when you tell it to print emp_name[1], it has no idea what emp_name[1] is because it sees a string at that point.
If you write, instead:
emp_name[0] = raw_input("please enter employee name")
That means you're assigning that employee name to element 0 of array emp_name.
Then you want to add index entries inside the while, rather than re-assigning them (you see, it doesn't automatically accumulate entries, you have to tell it to).
Happy Coding!
You can add to a list with list.append(), but you need to capture user input into a separate variable:
employees = []
emp_name = raw_input("Please enter employee name, enter neg to exit")
while emp_name != "neg":
emp_name = raw_input("Please enter employee name, enter neg to exit")
employees.append(emp_name)
print "employee 2 is:", employees[1]
Apart from using separate variables for the list of names and for the name the user has just entered, I also started the list entirely empty.
You can avoid using two raw_input() calls by changing the while loop to an infinite loop and instead break out of the loop when 'neg' has been entered:
employees = []
while True:
emp_name = raw_input("Please enter employee name, enter neg to exit")
if emp_name == 'neg':
break
employees.append(emp_name)
You may also need to test if there are enough employees entered before you print the second employee:
if len(employees) > 1:
print "Employee 2 is:", employees[1]
else:
print "You didn't enter enough employees!"
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.