I have been working on this for too long. It should be simple and I've ran through many different combinations, however, I keep getting the code wrong and have no idea why. It works fine when I have manual input, but when I submit there is an error.
question prompt:
Write a program that keeps a dictionary of names and their corresponding phone numbers.
Repeatedly ask the user for a name. Then, do one of the following three things, depending on what they enter:
If they enter nothing, exit the program.
If they enter a name that exists as a key in your dictionary, simply print the corresponding phone number.
If they enter a name that is NOT in your dictionary as a key, ask the user for a phone number, and then put the name and phone number in your dictionary.
Print out the final dictionary.
my code:
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook:
number = input("Please enter number: ")
print "Phone number: " + number
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name in phoneBook:
print phoneBook[name]
if name == '':
break
print phoneBook
Expected result:
Phone number: 1234
Phone number: 5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
My result:
Phone number: 1234
Phone number: 5678
Phone number: 9999
1234
Phone number: 9999
5678
Phone number: 9999
{'Tracy': '9999', 'Karel': '9999', 'Steve': '9999'}
you must also access the dictionary keys for checking the existence of a name:
if not name in phoneBook.keys():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook.keys():
number = input("Please enter number: ")
phoneBook[name] = number
print "Phone number: " + number
name = input("Please enter a name(or press enter to end input): ")
else:
print phoneBook[name]
print phoneBook
Try the above code.
When a name is not in the phoneBook, then assign the name a number, so phoneBook[name] = number should be in the if not name in phoneBook.keys(): block. And then enter another name in the same if block.
Related
I am trying to figure out how to create a sentinel code to allow the user to input a name and test score that will be listed in a text file. I just need the names to be in column one and scores in column two of the text file. I tried having the name and grade as a single input but was given errors. I am still getting an error for the code below.
Enter the students’ name and test score. Store entered data in a text file named Class.txt, and close the file. Use an empty string as a sentinel to stop the data entry. Make sure that program will accept only correct data for the student’s test scores.
def main():
outfile = open("Class.txt", 'w')
count = 0
student = input("Please enter a student's last name (<Enter> to quit): ")
grade = eval(input("Please enter the student's grade (<Enter> to quit): "))
while student != "" and grade != "":
count = count + 1
student = input("Please enter a student's last name (<Enter> to quit): ")
grade = eval(input("Please enter the student's grade (<Enter> to quit): "))
print(student, grade, file = outfile)
outfile.close()
main()
error:
grade = eval(input("Please enter the student's grade (<Enter> to quit): "))
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
You are sending an un-sanitized user input to eval - this is a very unsafe practice, and it is also what's causing an error when you try to use the sentinel (empty input for grade). You should not really be asking for grade if the name is empty.
To avoid repetition, you should place you should place your input calls in a function:
def get_data():
student = input("Please enter a student's last name (<Enter> to quit): ")
if student:
grade = input("Please enter the student's grade (<Enter> to quit): ")
if grade.isdigit():
return (student, int(grade))
return (None, None)
I added an implicit sentinel - if grade is not an natural number, then the loop will stop, too.
Then, you loop would look like this:
(student, grade) = get_data()
while student:
print(student, grade, file = outfile)
(student, grade) = get_data()
Note that I swapped the order of the input and output in the main loop, since in your original code the first input would have not been processed.
This code executes well, but I don't think this the best way to do it.
def bank_account(Name, number, username, passwrod):
Output = Name, number, username, passwrod
return Output
new_name = input ("Please Enter Your Name: ")
new_number = input ("What's your number please: ")
new_username = input ("Enter your UserName: ")
new_passwrod = input ("(Integers Only!) Enter your Passwrod Sir: ")
print("Your Data has been saved!", bank_account(new_name, new_number, new_username, new_passwrod))
Is there any other way to do it?
As the comments suggest, what you're trying to do is unclear!
Maybe something the bank_account function can do is validate the input?
For example you specify that the password must be numeric. For arguments sake let's say the same is true for the number. Also just assume that the name must only consist only of alphabetic letters.
def bank_account(name, number, username, password):
if not name.isalpha():
print('Your name must only contain letters!')
return 'Invalid'
try:
number = int(number)
password = int(password)
except ValueError:
print('Your number and password must be numeric!')
return 'Invalid'
return name, number, username, password
new_name = input("(alphas) Please Enter Your Name: ")
new_number = input("(ints) What's your number please: ")
new_username = input("Enter your UserName: ")
new_password = input("(ints) Enter your Password: ")
print("Your details:", bank_account(new_name,
new_number,
new_username,
new_password))
Hope this gives you an idea of something you can do with your bank_account function!
I need to ask a user how many people are booking in , max 8 people then take that amount and ask for user 1 details, user 2 details etc.save details to be printed later.Not sure what to I'm very new to python.
manager_name = raw_input("please enter managers Name: ")
email_address = raw_input("please enter your Email Address: ")
phone_number = raw_input("please enter your Phone number: ")
print("-----------------------------------------------------")
print ("Our Stuido can Accommodate up to max 8 musicians")
print("-----------------------------------------------------")
amount_of_band_members = int(raw_input("please enter the amount of band members"))
values = []
for i in range(amount_of_band_members):
values.append(int(input('Please enter Muscians Names & Insterments: ')))
manager_name = raw_input("please enter managers Name: ")
email_address = raw_input("please enter your Email Address: ")
phone_number = raw_input("please enter your Phone number: ")
print("-----------------------------------------------------")
print ("Our Stuido can Accommodate up to max 8 musicians")
print("-----------------------------------------------------")
amount_of_band_members = int(raw_input("please enter the amount of band members"))
if amount_of_band_members >8:
print ("Sorry we can only Accommodate maxuim 8 Musicians")
else :
print raw_input("please enter musicians and insterments")
while amount_of_band_members <8:
print raw_input("please enter next name")
amount_of_band_members +=1
Ok so i need to ensure that a phone number length is correct. I came up with this but get a syntax error.
phone = int(input("Please enter the customer's Phone Number."))
if len(str(phone)) == 11:
else: phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
You can't have
if:
else:
Because the else, being inside the first if block, doesn't have a corresponding if.
It should be:
if:
this
else:
that
You may try this to be asking for the phone number until it is correct:
phone = ""
while len(str(phone)) != 11:
phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
If you want to check also that the input is a number and not text, you should also trap the exception raised by int in that case, for example:
phone = ""
while len(str(phone)) != 11:
try:
phone = int(input("Please enter the customer's Phone Number."))
except ValueError:
phone = ""
phonumber.append(phone)
I have this program, and it is almost perfect but I need the dictionary to print on separate lines like so:
Please enter a name (or just press enter to end the input): Tom
Please enter Tom's phone: 555-5555
Please enter a name (or just press enter to end the input): Sue
Please enter Sue's phone: 333-3333
Please enter a name (or just press enter to end the input): Ann
Please enter Ann's phone: 222-2222
Please enter a name (or just press enter to end the input):
Thank you.
Your phonebook contains the following entries:
Sue 333-3333
Tom 555-5555
Ann 222-2222
Here is my code:
def main():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
number = input("Please enter number: ")
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name == '':
print("Thank You!")
print("Your phonebook contains the following entries:\n",phoneBook)
main()
Loop through the entries in your phonebook and print them one at a time:
for name, number in phoneBook.items():
print ("%s %s" % (name, number))
something like this:
strs = "\n".join( " ".join((name,num)) for name,num in phoneBook.items() )
print("Your phonebook contains the following entries:\n",strs)
if you dont want to write codes yourself, pprint could be an option:
import pprint
....
print("Your phonebook contains the following entries:\n")
pprint.pprint(phoneBook)
You can use format() to make your life easy:
for i in phoneBook.iteritems():
print("{0} {1}".format(*i))
my_dictionary = {}
while True:
name = str(input("Enter a name: "))
if name == "":
break
elif name in my_dictionary:
print "Phone Number: " + my_dictionary[name]
else:
phone_number = input("Enter this person's number: ")
my_dictionary[name] = phone_number
print my_dictionary