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.
Related
The Problem to Analyze and Implement
Implement an inventory system of parts and prices using two parallel lists. The user can choose
from 4 options in a menu: to add a part, search for a part and display its price, display
everything in inventory, or exit.
The menu continues to redisplay until the user chooses to exit the system.
Requirement 1 – search_inventory Function
Name of function: search_inventory
Input to function: list1, list2
Output from function: None
Functionality: 1. The input list1 will be the list of parts.
2. The input list2 will be the list of prices.
3. Prompt the user for the part to search for.
4. Implement linear search to search for the part in list1.
5. If it is found, display the corresponding price from list2.
6. If it is not found, display a message.
Requirement 2 – add_to_inventory Function
Name of function: add_to_inventory
Input to function: list1, list2
Output from function: None
Functionality: 1. Prompt the user for the part to add.
2. Append this value to list1.
3. Prompt the user for the price to add.
4. Append this value to list2.
Requirement 3 – display_inventory Function
Name of function: display_inventory
Input to function: list1, list2
Output from function: None
Functionality: 1. Print column headers.
2. Use a counter-controlled while loop to print the contents of
each list in two columns.
3. See the sample runs below for the format of the output.
4. The prices must display with two values after the decimal
and be right-aligned.
Requirement 4 – display_menu Function
Name of function: display_menu
Input to function: None
Output from function: User’s choice as an integer
Functionality: 1. Display the menu of choices as shown in the sample run.
2. Prompt the user for their choice and store this value as an
integer.
3. Return the user’s choice
Requirement 5 – Main Section of Program
Declare two empty lists: parts_list and price_list.
Call the display_menu function and save the return value.
Create a sentinel_controlled loop:
a. Within this loop, use a selection structure to check the return value from the display
menu function and call the appropriate function depending on the user’s choice.
b. Call the display_menu function and save the return value.
c. You will have to figure out what the sentinel value is. (Hint – when should this loop
end?)
My codes:
**
def search_inventory(parts_list, price_list):
name_part = input("Name of a part: ")
index = 0
part_found = False
while part_found == False and index < len(parts_list):
if name_part == parts_list[index]:
part_found = True
else:
index = index + 1
if part_found:
print("Name of part:", name_part)
print("Price of part:", price_list)
else:
print(name_part, "was not found in the list")
return
def add_to_inventory(parts_list, price_list):
add_part = input("Add to inventory: ")
parts_list.append(add_part)
add_price = input("Add price: ")
price_list.append(add_price)
print("Part added successfully")
return
def dispay_inventory(parts_list, price_list):
part_name = ""
part_price = 0
while part_name == parts_list and part_price == price_list:
print("Name of part: ", part_name)
print("Price of part:{0:.2f}", part_price)
return
def dislay_menu():
print("Welcome to JJC Inventory System")
print("1. Add to inventory")
print("2. Check price")
print("3. Display inventory")
print("4. Exit")
user_choice = int(input("Your choice: "))
return user_choice
parts_list = []
price_list = []
user_choice = 0
dislay_menu()
while (user_choice != 4):
if user_choice == 1:
add_to_inventory(parts_list, price_list)
elif user_choice == 2:
search_inventory(parts_list, price_list)
elif user_choice == 3:
dispay_inventory(parts_list, price_list)
else:
break
dislay_menu()
**
I think the problem is with the sentinel_controlled loop. I checked the return value from the display
menu function and called the appropriate function depending on the user’s choice.
I get stuck on the homework for the following question:
Create a program that paris a student's name to his class guide. The user should be able to enter as many students as needed and then get a printout of all the students' names and grades. The output should look like this:
Please give me the name of the student (q to quit):[INPUT]
Please give me their grade (q to quit): [INPUT]
[And so on...]
Please give me the name of the student (q to quit): > q
Okay, printing grades!
Student Grade
Student1 A
Student2 D
Student3 B
Student4 A
Here is what I have done so far:
def my_dict():
while True:
name=input("Please give me the name of the student (q to quit):")
grade=input("Please give me their grade:")
my_dict[name]=grade
if name=='q':
break
print("Ok, printing grades!")
print("Student\t\tGrade")
for name, grade in my_dict.items():
print("name: {}, grade: {}'.format(name, grade))
I know it is not right but I don't know how to pair the name and grade and how to print out all the keys and values from user input. Please let me know if you are willing to help out! Much appreciate
There are several issues here, one is a syntax error as #khelwood noted in the comments, the other one is that my_dict is both a function and (apparently) a non-defined dictionary.
I also break before adding to the dictionary, otherwise you'll end up with 'q' as a name in the dictionary (and the user having to input a grade of student "q").
You can define a local dictionary in the function and then return it, for example:
def get_dict_from_user():
user_input = {}
while True:
name = input("Please give me the name of the student (q to quit):")
if name == 'q':
break
# It is not clear if 'grade' means a letter grade (A-F) or a numerical grade (0-100).
# If you want numerical grade it may be better to do convert to int so you can do
# calculations, such as finding the average
grade = input("Please give me their grade:")
user_input[name] = grade
return user_input
grades_dict = get_dict_from_user()
print("Ok, printing grades!")
print("Student\t\tGrade")
for name, grade in grades_dict.items():
print('name: {}, grade: {}'.format(name, grade))
quarter1 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
quarter2 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
pick_q = int(raw_input("Pick a quarter: "))
if pick_q == 1:
assignment = 0
courses = int(raw_input("How many courses would you like to enroll? "))
print quarter1
while assignment < courses:
course = int(raw_input("Please select the course you'd like to enroll into(1-5): "))
newlist = []
chosen_assignment = quarter1[course]
newlist.append(chosen_assignment)
assignment += 1
print newlist
So I'm trying to make this program where a student can enroll to different courses within an specific quarter. I only put in 2 quarter as an example.
The problem I'm having is that I want to create a new list from the courses the student chooses, for example if he wishes Course1, 2 and 3 then a new list should be able to print "You have enrolled to [Course1,Course2, Course3]"
However when I run this and try to print the newlist it comes up when only the last pick the user entered in this case [Course3] and not with the other previous picks.
It doesn't necessarily have to print a list, but the user should be able to choose from the original list and gather this information to create new list. I put in a zero starting the list so that the user can pick a number from the list index 1-5. I'm new at python and trying to figure this thing out. Thank you in advance!!
Any other recommendations are really appreciated!!
Basically the newlist variable is being initialized again and again inside the loop. You simply need to declare it outside the loop.
quarter1 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-ourse5"]
quarter2 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
newlist = [] # Declare it outside
pick_q = int(raw_input("Pick a quarter: "))
if pick_q == 1:
assignment = 0
courses = int(raw_input("How many courses would you like to enroll? "))
print quarter1
while assignment < courses:
course = int(raw_input("Please select the course you'd like to enroll into(1-5): "))
chosen_assignment = quarter1[course]
newlist.append(chosen_assignment)
assignment += 1
print newlist
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.
What i have to do is have T number of test cases which is how many time i will
obtain the average of "n" number of students in each test case and i need to display the average score for each test case and the highest mark in that test case and the name of student
If you can tell me the proper way to code this and explain why it has to be that way i will greatly appreciate it! I am lost
My code:
t = int(input("enter number of cases: "))
def casing(t):
for case in range (1, t+1):
n = int(input("enter number of students: "))
def studentmarks(n):
total = 0
student = "none"
for computetotal in range(1,n+1):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
highestmark = mark
if studentmark(n) > mark:
highestmark = mark
achieve = student
return highestmark, acheive
return total, studentmark()[0], studentmark()[1]
average = float((studentmarks(n)[0])/ n)
print("average: ", average, "highest: ",studentmark(n)[1], "student: ", studentmark(n)[2])
I think the code, as it is, would be much simpler to understand and debug without the function declarations. Unless you're doing functional-style programming (e.g. passing around function objects) there's rarely a good reason to use nested functions. Here you're defining the functions, then immediately calling them once, which is fairly pointless. So here's a simplified version of your code:
t = int(input("enter number of cases: "))
for _ in range (t):
total = 0
highest_mark = 0
best_student = "none"
n = int(input("enter number of students: "))
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
if mark > highestmark:
highestmark = mark
beststudent = student
average = total / n
print("average: {}, highest: {}, student: {}"
.format(average, highestmark beststudent))
I also eliminated the function named studentmark (with no "s") which your code was calling but never defined. I'm not sure if I correctly interpreted what it was supposed to be doing, but I think so. It certainly wouldn't have worked before.
There are a few reasons this isn't working - but the root cause seems to be because your highestmark is started off in the wrong place. It looks like you later expect the student name and mark to be in a tuple, which is a good idea - but you never actually make this tuple anywhere. So, make one, and call it highest - it replaces both the student and highestmark variables. Start it as None instead of "none" (which could actually be a valid student name!), so you have above the loop:
total = 0
highest = None
and change your "is this one higher than the highest" logic to this:
if highest is None or mark > highest[1]:
highest = (name, mark)
Read as "if there is no highest student yet, or this one has a higher mark than the current highest, this one is the highest". Then you'll want the return to be:
return total, highest[0], highest[1]
But, since you only have a small amount of data (enough that it is feasible to have a user type it in at a console), then you can simplify this logic quite a bit. Read all of the data for a particular test case into a list of (student, mark) tuples, and then use Python's builtins to do the calculations:
def studentmarks(n):
marks = []
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
marks.append(student, mark)
return marks
# Calculations
marks = studentmarks(5)
print('Average: ', sum(result[1] for result in marks)/len(marks))
print('Highest: ', max(marks, key=lambda s: s[1])
Seeding it with:
>>> marks
[('Fred', 4), ('Wilma', 10), ('Barney', 8), ('Wilma', 7), ('Pebbles', 6)]
Gives an average of 7.0, and a maximum of ('Wilma', 10).