Python assignment for a phonebook - python

This weeks lab is based on the example on pages 53,54 of the wikibook "Non-Programmers Tutorial For Python" by Josh Cogliati (2005), (see http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Dictionaries).
In his example, Cogliati has options for printing, adding, removing, and looking up a phone number. Change the code so that, instead of the value in the dictionary being a simple phone number, it is now a list with three values:
phone number
e-mail
address web page
The key should still be simply the persons name. Adapt the menu used in the example accordingly, for example the '2. Add a Phone Number' should now read '2. Add an entry' and if selected should ask the user for the 4 items of information (name, phone, email, web). Aditionally:
Add an option (e.g. number 6 in the menu) to 'Change/Edit an existing entry'.
Add options to:
Print just a list of the phone numbers
Print just a list of the e-mail addresses
Print just a list of the web addresses
Print all of the above together
This is the assignment we were given, I understand what's given in the link and have added a bit to it, unsure as to how to go about adding in the calling upon of the email and webpage information once stored

Although I agree with the comment under your answer, I will still try my best to give you some guidance.
Original Code:
def print_menu():
print('1. Print Phone Numbers')
print('2. Add a Phone Number')
print('3. Remove a Phone Number')
print('4. Lookup a Phone Number')
print('5. Quit')
print()
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("Telephone Numbers:")
for x in numbers.keys():
print("Name: ", x, "\tNumber:", numbers[x])
print()
elif menu_choice == 2:
print("Add Name and Number")
name = input("Name: ")
phone = input("Number: ")
numbers[name] = phone
elif menu_choice == 3:
print("Remove Name and Number")
name = input("Name: ")
if name in numbers:
del numbers[name]
else:
print(name, "was not found")
elif menu_choice == 4:
print("Lookup Number")
name = input("Name: ")
if name in numbers:
print("The number is", numbers[name])
else:
print(name, "was not found")
elif menu_choice != 5:
print_menu()
Notice that numbers is equal to {} - this signifies that it is a "Dictionary", which stores key/value pairs. To add to a dictionary (or "dict"), you can modify it manually as such: numbers = {'David': 18003574689}. So, in order to access David's phone number, you would type in numbers['David'].
Another way to add to it is by instantiating it (which is already done for you via numbers = {}), and then adding information into to it via the shortcut formula dictname['key'] = value. So in this case, the shorthand can be numbers['Laura'] = 9173162546.
Now, to add a list into the mix, you could use [] (which is a list in python), but you would probably be better suited nesting another dict into the current one. For example, instead of numbers = {'David': 18003574689}, you can now have numbers = {'David': {'phone number': 18003574689, 'e-mail': 'david2015#gmail.com', 'address web page': 'http://dave.com'}, 'Laura': [...etc...]}.
To access these new nested dicts, what you can do is the shorthand numbers['David']['phone number'], which will return his #. You can then do this exact shortcode 2 more times numbers['David']['e-mail'] & numbers['David']['address web page']. These three will access the associated data.
Since I believe this is the toughest part for a newcomer, I'll stop here since the rest should be easy. All you have to do is create new inputs in the correct if conditions. Assign the captured input data into proper variables via the = assignment operator (ex. email = input('Email: ')), and then use the rest of the info logically. I hope this helps.

Related

Taking user input and appending it to a tuple? Python

So basically I'm trying to create a list of movies with their budgets, but I don't know how to take the input and place it into a tuple
movie_list = ()
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append(title, budget)
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
Tuples don't handle appending well. But lists do:
movie_list = [] # make a list, not a tuple
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append( (title, budget) ) # append a 2-tuple to your list, rather than calling `append` with two arguments
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
You can’t add elements to a tuple due to their immutable property. You can’t append for tuples.
Tuples are immutable in Python. You cannot add to a tuple.
A tuple is not a data structure like a list or an array. It's meant to hold a group of values together, not a list of the same kind of values.
I think I get what you want, my guess would be that you want a list of tuples. In that case, just change the first line variable to be a list.
I improved your code so your logic works:
movie_list = [] # movie_list is a list
while True:
title = input("Enter movie: ") # Use input() to get user input
budget = input("Enter budget: ")
movie_list.append((title, budget)) # Append a tuple to the list
# movie_list is now a list of tuples
# Check if the user wants to add another movie
more = None
# Loop until the user enters a valid response
while True:
more = input("Add another? (Y/N): ").upper()
if more in ("Y", "N"):
break
print("Invalid input")
# If the user doesn't want to add another movie, break out of the loop
if more == "N":
break
# Else, continue the loop
print(movie_list)
Coding apart, to write any program, first one should know the purpose of the program and its outcome. It would be better, if you can show here what the exact output you want, out of the created or appended list. As far as I understood your requirement, you should go with dictionary concept so that you can store data as pairs, like, movie and its budget.
{"movie":budget}
While taking input of budget, be sure whether you want to restrict the input value to an integer or you want to allow this as a string, like in crores. Hope this will help you.

Validate if its a string or not

I am not getting it right and I can't find how to do it.
Get the user input and create a thematic list of strings. The program should ask for a specific input theme.
The user should enter strings for the list until a condition is met such as entering a specific word or character.
There should not be hard coded list size.?
Each user input should be one list element.
MyList = []
for _ in range(5):
planets = str(input("Enter 5 planets: "))
if planets == str(planets):
if planets not in MyList:
MyList.append(planets)
else:
print("Input not valid")
print("That's your planets: ")
print(str(MyList))
I don't quite understand. To validate if something is a string should be isinstance(something, str). But input always returns a string. There is no need to do extra validation.
By the way, if you only want to eliminate duplicated items, I suggest using a set instead of a list. Call str() for print() is also redundant because print() will do the conversion itself. So:
print("Enter 5 planets: ")
result = {input(f"{i}) ") for i in range(1, 6)}
print("That's your planets:", ", ".join(result))
MyList = []
for _ in range(5):
planets = input("Enter 5 planets: ")
if type(planets) == str:
if planets not in MyList:
MyList.append(planets)
else:
print("Input not valid")
print("That's your planets: ")
print(",".join(MyList))
Actually any variable defined with the input() function will always be a str data type, because even if it's a number, it would still be the string representation of that number. Even if the user did not input any values ​​at all, it would still be an empty string "".
I'm not sure what kind of verification you are trying to do exactly on that input but if you want to verify that it's not a number you can use theisdigit() string method.
Here is a simple example:
planets = []
while True:
planet = input("Insert the name of a planet: ")
if planet == 'quit':
break
if not planet.isdigit() and not planet in planets:
planets.append(planet)
print("Here is your list of planets:")
for planet in planets:
print(planet)
This block of code continually prompts the user to enter a planet name until the keyword quit is entered. If the input is not a number and is not already in the planets list, it is added. Finally, the complete list of planets is shown.
It must be said that on a conceptual level this implementation does not make much sense. It would be more logical to have a list of all known planets and check if the entered input matches any of the entries in the list. In that case, checking if the string represents a number becomes rather pointless.

Building upon existing function

I was just playing around with functions in order to further my understanding of them and I was curious, is it at all possible to return the users first name and last initial using the following function without adding any additional functions?
name = raw_input("Please enter your full name: ")
def username(a):
print(a[0:6]+a[-1])
username(name)
If the length of input names can vary and number of names then you will have to use another function split and index. If the user can just enter a single name you will need to add an if or try...except.
a[:a.index(' ')]) will get the first name, from the beginning of the input to the first space
index returns ValueError if the character isn't found so if they might enter just first name surround with try...except
a.split()[-1][0] will get the first letter of the last name even if they enter more than two names (Billy Bob Joe -> Billy J)
name = raw_input("Please enter your full name: ")
def username(a):
print(a[:a.index(' ')]+' '+a.split()[-1][0])
username(name)
Your current function assumes a length of first and last name. You could try
print(a.split()[0] + ' ' + a.split()[1][0]). The split() will change the string to a list of two elements, element 0 is the first name and element 1 is the last name.
a[-1] will give you the last letter of your string, which it sounds like you don't want this for your purpose.
name = raw_input("Please enter your full name: ")
def username(a):
fullname = a.strip().split(' ')
if len(fullname) < 2:
print('Error: last name required')
print('Type: firstname <middle name> last name')
exit(1)
try:
print('%s %s' % (fullname[0], fullname[-1][0]))
except IndexError:
exit(1)
username(name)
This is how I have managed to implement the info that you folk have provided me.
'''
code to input full name and convert into username consisting of first + first
initial of last name or first and first initial of first name if input is one name.
'''
def fullname():
name = raw_input("Please enter your full name: ").lower()
try:
name = (name[:name.index(' ')]+''+name.split()[len(name.split())-1][0])
except:
name = name[0:]+name[0]
return name
# code to generate exponential numbers
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*"
power = power -1
print "=%d" % exponential
'''
code to generate interactive menu with an error return for incorrect selection and exit clause.
'''
ans=True
while ans:
print ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
ans=raw_input("What would you like to do? ").upper()
if ans=="U":
print fullname()
elif ans=="E":
print print_exponential()
elif ans=="Q":
print("\n Goodbye")
break
elif ans !="":
print("\n Error: Choice must be U, E or Q")

Python deleting tuple record in list

I'm trying to delete a tuple from my list, I've tried everything people have said but still no luck. I tried two methods, one time it removes the record even if it's not the name I want to remove, and the second doesn't remove at all.
record=[]
newrecord=[]
full_time=""
choice = ""
while (choice != "x"):
print()
print("a. Add a new employee")
print("b. Display all employees")
print("c. Search for an employee record")
print("d. Delete an employee record")
elif choice == "d":
delete = str(input("Enter the name of the employee you would like to remove from the record: "))
for d in record:
if d == delete:
record.remove(delete)
This doesn't remove anything.
If I change it to:
elif choice == "d":
delete = str(input("Enter the name of the employee you would like to remove from the record: "))
record = [n for n in record if delete in record]
It removes all if I do it this way.
Heres how i add to the list
choice = input("Choose an option (a to f) or x to Exit: ")
if choice == "a":
full_name = str(input("Enter your name: ")).title()
job_title = str(input("Enter your job title: ")).title()
while full_time.capitalize() != "Y" or full_time.capitalize() != "N":
full_time=input("Do you work full time (Y/N): ").upper()
if full_time.capitalize() == "Y":
break
elif full_time.capitalize() == "N":
break
break
hourly_rate = float(input("Enter your hourly rate: £"))
number_years = int(input("Enter the number of full years service: "))
record.append((full_name, job_title, full_time, "%.2f" % hourly_rate, number_years))
Given that the name is the first element in the record any checks against the name must be done against the first element of the tuple.
Previously you had:
record = [n for n in record if delete in record]
The first problem here is that you have to check against n and not record in your condition:
record = [n for n in record if delete in n]
The next issue is that this will only add a record to the list if delete is found within it.
It seems as though you want the inverse of this:
record = [n for n in record if delete not in n]
^^^
Now that in itself will not work because delete is a string and n is a tuple here, so we must combine this with the first fix. We then get:
record = [n for n in record if delete not in n[0]]
One thing I would note however is that if you are only using employee names as indexes it's probably much cleaner/easier to just use a dictionary with the employee name as keys and the other information as values. Given that a dictionary is an associative mapping between keys and values and your problem is exactly that I'd recommend changing your data structures.

Gradebook: Python

I'm stuck on writing this program. These are the instructions that were given to us.
As per the guidelines at the top of the assignment you may NOT import any modules. This
includes the statistics module.
The user should be displayed with a list of options from 1 to 5
If the user chooses 1 they should be prompted to enter a student's name and grade
If the student does not appear in the grade book, the student and the grade should be
added to the grade book
If the student is already in the grade book their grade should be changed to the value
given
If the user chooses 2 they should be prompted to enter a student's name.
That student should be removed from the grade book
If the student is not in the grade book then the grade book should not be modified
but also no error should be displayed.
If the user chooses 3 the names and grades of all students should be displayed in
alphabetical order
If the user chooses 4 the following statistics for the course should be displayed: Mean,
Median, and Mode
The median is the middle number in a list of sorted numbers
The mode is the value that appears most often
If more there are 2 or more more numbers that appear most often then you may display any of them.
If the user chooses 5 the program should terminate
If any other option is chosen the program should tell the user that it does not recognize
the option and ask the user for another choice.
All inputs besides the command choice will be valid.
You do not have to match the exact number of spaces I have in my output when
displaying grades and course statistics but there needs to be at least 1 space.
Hint: Break the problem down into small functions that each tackle one part of the
problem. For example have one function for inserting a student into the grade book, another for calculating the mean, etc.
This is what I have so far and there are a few errors:
def menuprint():
print('1. Add/modify student grade.\n')
print('2. Delete student grade\n')
print('3. Print student grades\n')
print('4. Display the course statistics\n')
print('5. Quit\n')
menuprint()
choice = 0
students = []
grades = []
def addmodify():
name_points = input('Enter name and points: ')
nameGrade_list = name_points.split()
name = nameGrade_list[0]
points = nameGrade_list[1]
students.append(name)
grades.append([points])
def stat():
for i in range(0,len(students)):
print("NAME:", students[i])
print ("GRADES:", grades [i])
def mean(list):
sum = 0
floatNums = [float(x) for x in list]
return sum(floatNums) / len(list)
while choice !=5:
choice = int(input('Your choice: '))
if choice == 1:
addmodify()
print('Enter name and points:')
elif choice == 2:
name = input('Enter name to delete:')
students.remove(name)
elif choice == 3:
gradelist()
print ('SS')
elif choice == 4:
print('Mean', mean(grades))
def mean(num_list):
sum = 0
floatNums = [float(x) for x in num_list]
return sum(floatNums) / len(num_list)
should fix it. list is a keyword and cannot be used anywhere in your code as a variable.

Categories