I can't get the right values from my dictionary. Any suggestions? - python

I have everything right in my code (I think) except the part where I get the correct names from my dictionary.
My code is:
studentdirectory = {"Andrew": ["Jane", "John"], "Betsy": ["Ellen", "Nigel"], "Louise": ["Natalie", "Louis"], "Chad": ["Mary", "Joseph"]}
def menu():
print
print ("Enter 1 to retrieve the mother's name of the child.")
print ("Enter 2 to retrieve the father's name of the child.")
print ("Enter 3 to retrieve the name of both parents of the child.")
print ("Enter 0 to quit.")
print
while True:
choice = input("Enter your choice now: ")
if (choice >= 0) and (choice<= 3) and (int(choice) == choice):
return choice
else:
print ("Your choice is invalid. Please try again with options 0 to 3.")
for key in studentdirectory:
mom = studentdirectory[key][0]
dad = (studentdirectory[key][1])
def main():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Enter the name of the child: ")
if studentdirectory.has_key(name):
if choice == 1:
print "The name of the child's mother is ", mom, "."
elif choice == 2:
print "The name of the child's father is ", dad, "."
else:
print "The name of the child's parents are ", mom, " and ", dad, "."
else:
print "The child is not in the student directory."
main()
I would like to keep my code as close to this as possible. I just need help in understanding how to get separate values in the dictionary, because right now for every mom and dad I only get Louise's parents back. How do i fix this??
This is Python Language.

You're getting the values of mom and dad in a loop, but overwriting them each time, so they're always set to the value of the last loop cycle (Louise in your case). You should define them when you need them only instead:
def main():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Enter the name of the child: ")
if studentdirectory.has_key(name):
mom = studentdirectory[name][0]
dad = studentdirectory[name][1]
if choice == 1:
print "The name of the child's mother is ", mom, "."
elif choice == 2:
print "The name of the child's father is ", dad, "."
else:
print "The name of the child's parents are ", mom, " and ", dad, "."
else:
print "The child is not in the student directory."

if studentdirectory.has_key(name):
mom = studentdirectory[key][0]
dad = (studentdirectory[key][1])
And delete the for key in studentdirectory loop part
Because when you get a student name in the main loop.Your original code only return a const mom and dad varible,which comes from your for loop above the main() defination.
And logically
You can only get the parents name after you have the child's name

Related

Trouble with saving and loading dictionary with class instances using pickle

New to programming and trying to learn how to store data using pickle. Essentially, what I'm trying to do is create an address book using classes stored in a dictionary. I define the class (Contact). It all worked, but when I tried to introduce pickling to store data from a previous session, I've created 2 errors that I've found so far.
1: If I select to load a previous address book, I cant update or view the class variables. It's almost like there are two different dictionaries.
2: I select not to load a previous address book and add a contact. When I add the contact and try to view the contacts, I'll get an "Unbound Error: local variable 'address book' referenced before assignment"
What am I doing wrong with pickling?
address_book= {}
class Contact:
def __init__(self,first_name,last_name, phone,company):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.company = company
def __call__(self):
print("Contact: %s \nPhone #: %s \nCompany: %s" %(self.name,self.phone,self.company))
def erase(entry):
del address_book[entry] # delete address book entry
del entry #delete class instance
def save():
new_file = open("addressBook.pkl", "wb")
saved_address = pickle.dump(address_book, new_file)
new_file.close()
def load():
open_file = open("addressBook.pkl", "rb")
address_book = pickle.load(open_file)
open_file.close()
print(address_book)
return address_book
def add_contact():
first_name = input("Please type the first name of the contact. ")
last_name = input("Please type in the last name of the contact. ")
if " " in first_name or " " in last_name:
print("Please do not add spaces to your first or last name.")
else:
phone = input("Please type the user phone number without hyphens. ")
if not phone.isnumeric():
print("That isn't a valid phone number.")
else:
company = input("Please type the company they work for. ")
contact = Contact(first_name,last_name,phone,company)
address_book[first_name + " " +last_name] = contact #assign key[first and last name] to value[the class instance] in dictionary
def view_contact(entry):
if entry in address_book:
print("First Name: %s" %(address_book[entry].first_name)) #get class variables
print("Last Name: %s" %(address_book[entry].last_name))
print("Phone Number: %s" %(address_book[entry].phone))
print("Company: %s" %(address_book[entry].company))
else:
print("That person isn't in your address book")
def update(entry):
if entry in address_book:
update_choice = input("Would you like to update the first name (f), last name (l), phone (p), or company (c)? ").lower()
if update_choice == "f":
address_book[entry].first_name = input("Please type the updated first name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry] #delete old key
elif update_choice == "l": #update last name
address_book[entry].last_name = input("Please type the updated last name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry]
elif update_choice == "p":
address_book[entry].phone = input("Please type the updated phone number of this contact. ")
elif update_choice == "c":
address_book[entry].company = input("Please type the updated company of this contact. ")
else:
print("That was not valid. Please try again.")
def main():
print("Welcome to your address book!!")
returning_user = input("Would you like to load a previous address book? Y or N ").lower()
if returning_user == "y":
address_book = load()
while True:
choice = input("Please type A:Add, B:View All Contacts, V:View a Contact, D:Delete, U:Update, or X:Exit ").lower()
if choice == "x":
break
elif choice == "a":
add_contact()
elif choice == "b":
if len(address_book) == 0: #error check if no contacts
print("You don't have any friends. PLease go make some and try again later. :(")
else:
for i in address_book:
print(i)
elif choice == "v":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
view = input("Who do you want to view? Please type in their first and last name. ")
view_contact(view)
elif choice == "d":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
contact = input("Please type the first and last name of the person you want to delete ")
if contact in address_book:
erase(contact)
elif choice == "u":
if len(address_book) == 0:
print ("C'mon, you don't know anyone yet. How about you make some friends first?")
else:
choice = input("What is the first and last name of the person you'd like to update? ")
update(choice)
else:
print("That was not valid. Please try again.")
print()
save_book = input("Would you like to save your book? Y or N ").lower()
if save_book == "y":
save()
print("Thanks for using the address book!")
main()

Why is my if true/elif/else-code not working?

In python, I am trying to make this code accept the user to move forward if he writes "True", and not if he writes "False" for the statement in User_Answer. When I run the code however, I get the "the answer is correct!"-part no matter what I write. The part I am having trouble with starts with "Test_Answer".
Could anyone help me with this?
name_list = ["Dean", "Bill", "John"]
enter_club = ["Enter", "enter"]
print ("THE CLUB - by Mads")
print (" ")
print ("""You approach a secret club called \"The club\". The club members are dangerous.
Make sure you tell the guard one of the members names.""")
print ("")
print ("Good evening. Before you are allowed to enter, we need to check if your name is on our list.")
def enter_the_club():
enter_now = input(" \nPress \"enter\" to enter the club... ")
if (enter_now in enter_club) == True:
print (" ")
print ("But as you enter, you are met with an intelegence test. \n It reads:")
check_name = input("What is your name? ")
def list_check():
if (check_name in name_list) == True:
print("Let me check.. Yes, here you are. Enjoy yourself, %s!" % check_name)
enter_the_club()
elif check_name.isalpha() == False:
print("Haha, nice try %s! Let's hear your real name." % check_name)
list_check()
elif (check_name in name_list) == None:
print ("You will need to give us your name if you want to come in.")
list_check()
else:
print ("I am sorry, but I can not find your name on the list, %s." % check_name)
print ("Are you sure that's your listed name?")
list_check()
list_check()
print ("But as you enter, you are met with an intelegence test.")
print (" ")
print ("It reads:")
Test_Answer = True
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
IQtest()
True is a boolean constant. What the user enters will be either "True" or "False", both character strings. Also, your elif condition cannot be true. What are you trying to do with three decision branches?
Without changing your code too much ... try this?
Test_Answer = "True"
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
Note that I've also corrected your "else" syntax.
Also, you have no value for check_name; I assume this is a global variable that you've handled elsewhere.

Allowing users to create multiple list in Python

I want to user to input information and print out the total list. However, when the user input another list it only prints out the first list. How can I make the program print the users total input. Here's my code.
listing = []
class Car:
def __init__(self, ownerName=None, model=None, make=None, price=None):
self.ownerName = ownerName
self.model = model
self.make = make
self.price = price
def input(self):
print "Please update car info \n"
while True:
i = 0
listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
print "Updated"
print listing[i].ownerName, listing[i].model, listing[i].make, listing[i].price
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() == "y":
i += 1
continue
else:
break
# search a car and print its information. Exit when user input is 'exit'
def menu():
x = Car()
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) search a car and print info\n" \
"\"exit\" Exit")
if choice == "1":
x.input()
elif choice == "2":
print "Price"
elif choice == "3":
print "Search and Print info"
menu()
#mhawke's answer should fix your problem. However, I do not like the idea of creating objects of a class from one of its functions. Check the edited code below.
listing = []
class Car:
def __init__(self, ownerName=None, model=None, make=None, price=None):
self.ownerName = ownerName
self.model = model
self.make = make
self.price = price
def input_car():
print "Please update car info \n"
i = 0
while True:
listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
print "Updated"
print listing[i].ownerName, listing[i].model, listing[i].make, listing[i].price
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() == "y":
i += 1
continue
else:
break
# search a car and print its information. Exit when user input is 'exit'
def menu():
#x = Car()
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) search a car and print info\n" \
"\"exit\" Exit")
if choice == "1":
input_car()
elif choice == "2":
print "Price"
elif choice == "3":
print "Search and Print info"
menu()
I cleaned up the code a little bit. I should work now. Option 3 gives you a complete listing of all cars so far, so youhave an example to build on.
listing = []
class Car:
def __init__(self, ownerName=None, model=None, make=None, price=None):
self.ownerName = ownerName
self.model = model
self.make = make
self.price = price
#to have a useful method for our example I overwrite the __str__ method from object
def __str__(self):
return ",".join([self.ownerName, self.model, self.make, self.price])
#input does not handle aspects of car, therefore it should be not a method of car
def input():
print "Please update car info \n"
while True:
# there is no need for 'i' so I removed it
car = Car(raw_input("Owner Name"),
raw_input("Model?"),
raw_input("Make?"),
raw_input("Price?"))
listing.append(car)
print "Updated"
print car #possible since __str__ is overwritten
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() == "n":
break
def menu():
keep_running = True
#added a while loop so the user stays in the program until he types 'exit'
#changed option '3' to have a working example to build on
while keep_running:
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) list all cars\n" \
"\"exit\" Exit")
if choice == "1":
input()
elif choice == "2":
print "Price"
elif choice == "3":
print "\n".join(map(str, listing))
elif choice == "exit":
keep_running = False
menu()
That's because you reset i on each iteration of your while loop.
Move the line:
i = 0
to the line before the while True:
That should fix the immediate problem, however, your code uses an unusual design. You should not create a Car object in order to create further instances of Cars which are then inserted into a global list.
At a minimum you could make input() a static method and have it return a list of Car instances to the caller. Then you can do away with the global listing variable. Also, you don't actually need to keep a counter in i you can just use -1 as the subscript to access the last item in the list:
#staticmethod
def input(listing=None):
if listing is None:
listing = []
print "Please update car info \n"
while True:
listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
print "Updated"
print('{0.ownerName} {0.model} {0.make} {0.price}'.format(listing[-1]))
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() != "y":
break
return listing
Using a static method is good here because input() is related to Car objects so it makes sense to package that function with the class.
Now you can call input() without creating an instance of a Car. In your menu() function remove the x = Car() and change x.input() to listing = Car.input(). Or, if you want to append to an existing "listing" list, call Car.input(listing) which will append new input to listing. You can then print the returned list to see all user input:
def menu():
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) search a car and print info\n" \
"\"exit\" Exit")
if choice == "1":
listing = Car.input()
# print out all user entered cars
for car in listing:
print('{0.ownerName} {0.model} {0.make} {0.price}'.format(car))
elif choice == "2":
print "Price"
elif choice == "3":
print "Search and Print info"

Python - I can only save one thing with append?

Here is my code. I can't save more than 1 thing in the list, I don't know why.
The point of the program is to save words (like "banana") and then add a description to it ("yellow"). I'm using Python 2.7
word = []
desc = []
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word.append(raw_input("Word to insert: "))
desc.append(raw_input ("Description of word: "))
main_list()
def look():
up = raw_input("Word to lookup: ")
i = 0
while up != word[i]:
i+1
print "Description of word: ", desc[i]
main_list()
You're not updating the value of i. You're calling i+1 which doesn't really do anything (it simply evaluates i + 1 and discards the result). Do instead i += 1 which seems to work.
Furthermore that's a rather strange approach to creating a dictionary, when you have a built-in data structure for that - the dictionary ({}).
In general, you should not use two list to save the words and their respective descriptions.
This is a classic case for using a dictionary, which will also help you once you have a lot of words, as you do not need to loop over all entries to find the corresponding description.
words = {}
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word = raw_input("Word to insert: ")
desc = raw_input ("Description of word: ")
words[word] = desc
main_list()
def look():
up = raw_input("Word to lookup: ")
print "Description of word: ", words.get(up, "Error: Word not found")
main_list()

Inputting scoring (python 2.7.5)

I'm having trouble inputting scoring in my python quiz code. Here is the script:
#This is the Test script for )TUKT(, Developed by BOT.
print ""
print "Welcome to the Ultimate Kirby Test."
print ""
begin = (raw_input("Would you like to begin?:"))
if begin == "yes":
print ""
print "Alright then! Let's start, shall we?"
print "Q1. What color is Kirby?"
print "1) Black."
print "2) Blue."
print "3) Pink."
print "4) Technically, his color changes based on the opponent he swallows."
choice = input("Answer=")
if choice ==1:
print "Incorrect."
print ""
elif choice ==2:
print "Incorrect."
print ""
elif choice ==3:
print "Tee hee.... I fooled you!"
print ""
elif choice ==4:
score = score+1
print "Well done! You saw through my trick!"
print ""
elif choice > 3 or choice < 1:
print "That is not a valid answer."
print ""
print "Well done! You have finished my test quiz."
print("Score:")
print ""
#End of Script
The error always says
score = score+1 is not defined.
I did not get anywhere researching.
Thanks! Help is very much appreciated!
You forgot to define a variable called score. You can't reference a value that doesn't exist!
Just declare it at the start:
score = 0
In the line score = score + 1, Python goes: 'so I need to create a variable called score. It contains the value of score, plus 1.' But score doesn't exist yet, so an error is thrown.
The varibale score has never been defined. Insert score = 0 as first line of your scirpt.

Categories