I really do not know how to describe this but I'll include an output in preformatted text after my horrific explanation.
So... I create three lists I need to use two, 'employeeSold' and 'employeeName,' however I need to merge/align the two so I can make a ranking system on who's got the most, I figured out how to order from largest to most significant for employeeSold, but I am most unsure on how to link the correct Name to the correct value, I figured it needs to come before the ordering though, but I really do not know what to type and I've spent a handful of hours thinking about it.
Here is an example OUTPUT of what I want for this code:
Ranking:
John - 5
Laura - 4
BOJO -1
It has assigned each integer (employeeSold) to each string (employeeName) and then ordered the integers (employeeSold) inserted by the user from largest to most significant and then printed their names next to their integer.
Here is my code:
def employee():
employeeName = input("What is Employee's name?: ")
employeeID = input("What is Employee's ID?: ")
employeeSold = int(input("How many houses employee sold?: "))
nameList.append(employeeName)
idList.append(employeeID)
soldList.append(employeeSold)
nextEmployee = input("Add another employee? Type Yes or No: ")
if nextEmployee == "2":
employee()
else:
print("Employee Names:")
print(", ".join(nameList))
print("Employee's ID: ")
print(", ".join(idList))
print("Employee Sold:")
print( " Houses, ".join( repr(e) for e in soldList ), "Houses" )
print("Commission: ")
employeeCommission = [i * 500 for i in soldList]
print(", ".join( repr(e) for e in employeeCommission ), "" )
print("Commission Evaluation: ")
totalCommission = sum(employeeCommission)
print(totalCommission)
soldList.sort(reverse=True)
print("Employee Ranking: ")
ranking = (", ".join( repr(e) for e in soldList))
print(ranking)
nameList = []
idList = []
soldList = []
employee()```
--------
Any help would be very much so appreciated.
You could consider breaking up your logic into multiple functions and sorting a zip of the names, and num_houses_sold list to print a ranking as you specified:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
def get_single_employee_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
names.append(input('What is the employee\'s name?: '))
ids.append(get_int_input('What is the employee\'s id?: '))
num_sold_houses.append(
get_int_input('How many houses did the employee sell?: '))
def get_houses_sold_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
while add_another_employee:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input(
'Add another employee [yes/no]?: ')
def print_entered_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
for values in zip(*[names, ids, num_sold_houses, commission]):
print(' '.join(f'{v:<{row_width}}' for v in values))
print()
total_commission = sum(commission)
print(f'Total Commission: {total_commission}')
print()
rankings = sorted(zip(num_sold_houses, names), reverse=True)
print('Ranking:')
for houses_sold, name in rankings:
print(f'{name} - {houses_sold}')
def main() -> None:
print('Houses Sold Tracker')
print('===================')
names, ids, num_houses_sold = [], [], []
get_houses_sold_info(names, ids, num_houses_sold)
print_entered_info(names, ids, num_houses_sold)
if __name__ == '__main__':
main()
Example Usage:
Houses Sold Tracker
===================
What is the employee's name?: Laura
What is the employee's id?: 1
How many houses did the employee sell?: a
Error: Enter an integer, try again...
How many houses did the employee sell?: 4
Add another employee [yes/no]?: yes
What is the employee's name?: John
What is the employee's id?: 2
How many houses did the employee sell?: 5
Add another employee [yes/no]?: y
What is the employee's name?: BOJO
What is the employee's id?: 3
How many houses did the employee sell?: 1
Add another employee [yes/no]?: no
Name Id Houses Sold Commission
Laura 1 4 2000
John 2 5 2500
BOJO 3 1 500
Total Commission: 5000
Ranking:
John - 5
Laura - 4
BOJO - 1
As an aside if you ever make something real don't use a sequential user id, the amount of information you can obtain from just monitoring this is insane, e.g., the rate of user acquisition, which you don't want external people to be able to figure out.
You can use zip function to merge lists and then custom key sorting.
SortByName function returning the sort key name and SortBySalary function returning key salary
def SortByName(FullList):
return FullList[0]
def SortBySalary(FullList):
return FullList[2]
NamesList=['John','Laura','Bojo']
IdList=[1,2,5]
SalaryList=[2000,1000,5000]
ZippedList=zip(NamesList,IdList,SalaryList)
print ZippedList
# result
#[('John', 1, 2000), ('Laura', 2, 1000), ('Bojo', 5, 5000)]
ZippedList.sort(key=SortByName,reverse=True)
print ZippedList
# result
# [('Laura', 2, 1000), ('John', 1, 2000), ('Bojo', 5, 5000)]
ZippedList.sort(key=SortBySalary,reverse=True)
print ZippedList
# result
# [('Bojo', 5, 5000), ('John', 1, 2000), ('Laura', 2, 1000)]
If you later want to sort the lists by id, just implement id sorting function.
def SortByID(FullList):
return FullList[1]
ZippedList.sort(key=SortByID)
Related
My code below works as long as all of the student's name consists of only two names - ex. Julie Andrews. But, when generating the student's emails, I'm trying to account for the students who have two first names - ex. Mary Jane Stewart. I want it to output something like MJStewart123#gmail.org, vs. what my current code will print, which is MJane123#gmail.com - totally ignoring the student's last name.
After hours of researching Google, I have tried updating my create_emails fx to change my original variable first_last = name.split(" ") to something like first, middle, last = name.split(" ") or first_last = name.split(" ", 2) while also, respectively, updating the line utilizing the attribute .append from its original to student_emails.append(first_last[0][0] + first_last1 + first_last[2]+ last_three_sid + "#gmail.com") or student_emails.append(first[0] + middle[0] + last + last_three_sid + "#gmail.com"). All attempts have obviously returned some form of an error...
The attached Stack Overflow article is the closest thing I could find whose logic might be applicable to what I'm trying to accomplish here, specifically the comment by Manfred, but in reading it, I don't know how to apply what they've done to my program... because I don't quite understand what it is that I'm reading... since I'm such a newbie at all this. I'd appreciate any help you can offer.
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
first_last = name.split(" ")
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(first_last[0][0] + first_last[1] + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Finding and first and middle initials in a list of names in python
You could do it like this I guess:
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
email_name = ""
first_last = name.split(" ")
for i, v in enumerate(first_last):
if i > len(first_last)-2:
break
email_name+=v[0]
email_name = email_name+first_last[-1]
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(email_name + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Result:
Enter student name, please. Julie Andrews
Enter student name, please. Mary Jane Stewart
Enter student name, please. Jack Hendricks
Enter student name, please. Maria Basset Juliett
Enter student name, please. Marco Hansen
name: Julie Andrews
id: 742536
email: JAndrews536#gmail.com
name: Mary Jane Stewart
id: 823274
email: MJStewart274#gmail.com
name: Jack Hendricks
id: 590875
email: JHendricks875#gmail.com
name: Maria Basset Juliett
id: 982168
email: MBJuliett168#gmail.com
name: Marco Hansen
id: 671240
email: MHansen240#gmail.com
The code is too redundant and could be implemented with some simpler structures.
name construction can use split combined with join function
storage can also use dictionaries to store multiple information about the same object, compared to multiple lists so more concise and efficient
The code itself is not a big problem, mainly the syntax structure requires more skilled,let's encourage each other in our endeavours
try this:
import random
info = []
# You can use for loop if you already know how many times it will loop
for i in range(5):
name = input("Enter student name, please:") # get name
student_id = random.randint(111111, 999999) # get id
name_structure = name.split()
email = "{name_abbr}{last_name}{sid}#gmail.com".format(
name_abbr="".join([item[0] for item in name_structure[:-1]]), # Generate initials
last_name=name_structure[-1], # Generate the last part of the name
sid=str(student_id)[-3:] # Generate the id in the mailbox
)
info.append({"name": name, "id": student_id, "email": email}) # Store to the list, or print directly
# Print Information
for item in info:
print("name:", item["name"])
print("id:", item["id"])
print("email:", item["email"])
print()
I'm aiming to display records of employees with a salary between 2 user inputted values (in a format specified in my function printTuple(data)). So far I use the function choice2() to open the file, read line by line in a for loop, convert the line (which is a string) to an int, then grab the index of the salary so I can compare it to the 2 inputted values (. After that I take the line as a variable in "record" and go to makeTuple to turn it into a tuple, and then finally print it in my desired format inside printTuple.
When I attempt to run the choice2 function I get an error: "local variable 'myTuple' referenced before assignment". However I need to change the myTuple value to an int before I can compare it with the values the user inputted, so I'm not sure how to fix this.
Here is my program:
def makeTuple (employee):
myTuple = employee.split(" ")
(payroll, salary, job_title, *othernames, surname) = myTuple
return(myTuple)
def printTuple (data):
employee_str = "{:<15} {:20} {:<10} {:<15} £{:>1}"
print(employee_str.format(data[-1]+ ",", " ".join(data[3:-1]), data[0], data[2], data[1]))
def choice1():
op_1 = str(input("Please enter a Pay Roll number: "))
file = open(path)
lines = file.readlines()
for line in lines:
if op_1 in line:
record = line.strip()
myTuple = makeTuple(record)
printTuple(myTuple)
def choice2():
op_2a = int(input("Please enter a lower bound for the Salary :"))
op_2b = int(input("Please enter a higher bound for the Salary :"))
file = open(path)
lines = file.readlines()
for line in lines:
myTuple[0] = int(myTuple[0])
if myTuple[0] >= op_2a and myTuple[0] <= op_2b:
myTuple[0] = myTuple[0]
record = line.strip()
myTuple = makeTuple(record)
print(myTuple)
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
f = open(path)
except IOError:
print('The file could not be opened.')
exit()
for line in iter(f):
record = line.strip()
myTuple = makeTuple(record)
printTuple(myTuple)
print("\n\nDisplay full details of an Employee with a given payroll number enter: '1'")
print("Display all employees with a salary within a specified range, enter: '2'")
print("Display the first and last name of all employees with a job title, enter: '3'")
print("Quit Program: '4'")
choice = int(input("Choose an option from 1-4: "))
while choice != 1 and choice != 2 and choice != 3 and choice != 4:
print("Incorrect Value, please choose a number from 1-4")
print("\n\nDisplay full details of an Employee with a given payroll number enter: '1'")
print("Display all employees with a salary within a specified range, enter: '2'")
print("Display the first and last name of all employees with a job title, enter: '3'")
print("Quit Program: '4'")
choice = int(input("Choose an option from 1-4: "))
if choice == 1:
choice1()
if choice == 2:
choice2()
if choice == 3:
choice3()
if choice == 4:
exit()
This is the text file I am reading from:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
12349 30000 Wizard Harry Potter
12350 15000 Entertainer Herschel Shmoikel Krustofski
13123 75000 Consultant Zlatan Ibrahimovic
13124 150000 Manager Gareth Southgate
13125 75000 Manager Juergen Klopp
13126 35000 Lecturer Mike T Sanderson
13127 200000 Entertainer Adele Laurie Blue Adkins
13128 50 Timelord Peter Capaldi
13129 250000 Entertainer Edward Christopher Sheeran
13130 32000 Secretary Wilma Flintstone
Any help is appreciated, thanks in advance.
Your error message (local variable myTuple referenced before assignment) points out the required solution. I have:
reordered (record = line.strip() and myTuple = makeTuple(record) to top of loop)
renamed some variables (myTuple is not very descriptive, and is actually a list anyway, better naming makes code much easier to read and reason about)
heavily commenting (I would not normally comment my own code this much, more as indications of what I have done and why)
Here is the updated code for choice2
def choice2():
lower_bound = int(input("Please enter a lower bound for the Salary :")) # Renamed for clarity
upper_bound = int(input("Please enter a higher bound for the Salary :")) # Renamed for clarity
# The following two lines are repeated multiple times, you should probably read
# the file once and store into a list (or better yet a dictionary
# keyed with pay roll number) and pass it into the function.
file = open(path)
lines = file.readlines()
for line in lines:
record = line.strip()
employee_details = makeTuple(record) # Rename muTuple to employee_details
# OR MORE SIMPLY employee_details = makeTuple(line.strip())
# Now we have the variable we can work with it
salary = int(employee_details[0]) # The only thing we do with the tuple is print it, so no need to modify it
if salary >= lower_bound and salary <= upper_bound:
# This does nothing, so deleted - myTuple[0] = myTuple[0]
print(employee_details) # Or more likely you want to use your custom print function printTuple(employee_details)
This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this.
Name ****
Phone Number ****
Jersey Number ****
Im new to dictionaries but I have spent hours reading and searching over the past couple of days about dictionaries and have tried several different ways to do this but failed. I have gotten the closest the way I have it setup now but it still doesnt work right. I feel like I am storing the information incorrectly into the dictionary for starters, any help would be greatly appreciated.
player_roster = {}
def display_roster(self): #Print Roster
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x, 'Phone Number:', player_roster[x])
else: #Print No One on Roster
len(player_roster) == []
print('No names have been entered:')
def add_player(self,): #Enter Members Name
name = input('Enter New Players Name:')
phone_number = input('Enter Players Phone Number:')
jersey_number = int(input('Enter Players Jersey Number'))
player_roster[name] = phone_number, 'Jersey Number', jersey_number
#If I input Toby as Name 444-444 as Phone Number and 3 as Jersey number it outputs like this
Name: Toby Phone Number: ('444-4444', 'Jersey Number', 3)
# I would like it to output like
Name: Toby
Phone Number: 444-4444
Jersey Number: 3
There are some things i would change in your code but to keep this close to what you asked for take a look at this:
def display_roster():
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x)
print('Phone Number:', player_roster[x][0])
print('Jersey Number:', player_roster[x][1])
else:
print('Roster is empty.')
return
player_roster = {}
def add_player():
name = input('Enter New Players Name:\t')
phone_number = input('Enter Players Phone Number:\t')
jersey_number = int(input('Enter Players Jersey Number:\t'))
player_roster[name] = [phone_number, jersey_number]
return
add_player()
display_roster()
# PRINTS:
#Name: Toby
#Phone Number: 444-4444
#Jersey Number: 3
Printing in multiple lines gives you the result you want. As stated in the comments this can also be done with a single print() statement but i do not think compact code makes much difference to you yet.
Further, this len(self.player_roster) == [] line does not make sense. This is as good as simply writing True in a line. The "emptiness" of the team is checked by the else:.
Finally, i would slightly change the way players are stored in the "Roster" dictionary and have it like this: {"Toby": ['444-4444', 3], ...}
I would propose that you replace the print statement to this:
print(" Name: %s \n Phone Number: %s \n Jersey Number: %d") % player_roster[x]
You're pretty much there. The below modification would allow you to print as you need (and is slightly more readable):
class PlayerDictionary():
def __init__(self):
pass
player_roster = {}
def display_roster(self): #Print Roster
if len(self.player_roster) != 0:
for key, value in self.player_roster.iteritems():
print(str(key) + ": " + str(value))
else: #Print No One on Roster
len(self.player_roster) == []
print('No names have been entered:')
def add_player(self,):
self.player_roster['Name'] = input('Enter New Players Name:')
self.player_roster['Phone Number'] = input('Enter Players Phone Number:')
self.player_roster['Jersey Number'] = int(input('Enter Players Jersey Number'))
if __name__ == "__main__":
player = PlayerDictionary()
player.add_player()
player.display_roster()
A slightly more maintainable solution would be to create a class for Player. Set the properties on the object and overload the str function e.g.
class Player(object):
def __init__(self):
self.__name = ""
self.__phone_number = ""
self.__jersey_number = ""
#property
def name(self):
return self.__name
#property
def phone_number(self):
return self.__phone_number
#property
def jersey_number(self):
return self.__jersey_number
#name.setter
def name(self, val):
self.__name = val
#phone_number.setter
def phone_number(self, val):
self.__phone_number = val
#jersey_number.setter
def jersey_number(self, val):
self.__jersey_number = val
def __str__(self):
return ("Name: %s\nPhone Number: %s\nJersey Number: %s" % (str(self.__name), str(self.__phone_number), str(self.__jersey_number)))
if __name__ == "__main__":
player = Player()
player.name = input('Enter New Players Name:')
player.phone_number = input('Enter Players Phone Number:')
player.jersey_number = int(input('Enter Players Jersey Number'))
print(player)
I am working with an external file which has data in the form of:
-12345 CSEE 35000 Bart Simpson
-12346 CSEE 25000 Harry Potter
-12350 Economics 30000 Krusty The Clown
-13123 Economics 55000 David Cameron
With the first item being the ID, the second the subject, the third the salary, and the rest being the name of the person.
In part of my program I am trying to print the information of the people who have salaries between values submitted by the user. I have put all the data in a list called lecturers then I put all the salaries in a separate list called lecturers salary and tried to make them integers because at first I thought the reason the for loop wasn't working was because when trying to access them from the lectures loop I thought they might still be part of a string at this point.
I have already used a loop in my program to print all the people who teach a specific subject. This subject is submitted by the user. I tried to use a for loop again for the salaries but its not working.
print""
# To God be the Glory
lecturer = []
lecturer_salary = []
x = 0
a = " "
print ""
String = raw_input("Please enter the lecturers details: ")
print ""
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
ID_Subject = " ".join(String[0:2])
money = String[2]
print "%s,%s %s %s" % (lastname,firstnames,ID_Subject,money)
printFormat(String)
while x < len(lecturer):
lecturer_salary.append(int(lecturer [x][2]))
x = x + 1
print ""
try:
fname = input("Enter filename within " ": ")
with open(fname) as f:
for line in f:
data = line.split()
printFormat(line)
line = line.split()
lecturer.append(line)
except IOError as e :
print("Problem opening file")
print ""
print ""
answer = raw_input("Would you like to display the details of lectureers from a particular department please enter YES or NO: ")
if answer == "YES" :
print ""
department = raw_input("Please enter the department: ")
print ""
while x < len(lecturer) :
for line in lecturer:
if lecturer[x][1] == department:
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
**elif answer == "NO" :
print ""
answer2 = raw_input ("Would you like to know all the lecturers within a particular salary range: ")
print ""
if answer2 == "YES":
lower_bound = int(input("Please enter the lower bound of the salary range: "))
upper_bound = int(input("Please enter the upper bound of the salary range: "))
print ""
while x < len(lecturer) :
for line in lecturer_salary:
if lower_bound < lecturer_salary[x] < upper_bound :
print lecturer_salary[x]
x = x + 1**
else:
print ""
print "Please enter a valid input"
So, you have an array of lecturer and one of lecturer salary. the
for line in lecturer_salary:
is not needed - just the while followed by the if. Note that this will only print out the salary, not the lecturer details. Since x is the index to both arrays you can access lecturer[x] for the rest. In truth you don't need the lecturer_salary at all, just walk through lecturer and check:
while x < len(lecturer) :
if lower_bound < lecturer[x][2] < upper_bound :
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
For starters, you shouldn't name your variable with a capital letter like String or Id_Subject.
It is simpler to break code into functions and try using a dictionary or class to improve readability and extensibility.
Here is a minimal code using class:
lecturers = [] # To store Lecturer instances, which isn't necessary
class Lecturer():
def __init__(self, id, subject, salary, name):
self.id = id
self.subject = subject
self.salary = salary
self.name = name
def readfile(filename):
"""read each line in a file and yield a list of fields"""
with open(filename, "r") as f:
for line in f.readlines():
# return a list of fields
yield line.replace("\n", "").split()
def new_lecturer(detail):
"""Return a new lecturer instance from a list of fields"""
return Lecturer(detail[0],
detail[1],
detail[2],
{"firstname": detail[3],
"lastname": detail[4]
})
def print_lecturer_detail(lecturer):
"""Accept a lecturer instance and print out information"""
print "{0},{1} {2} {3}".format(lecturer.name["lastname"],
lecturer.name["firstname"],
lecturer.id,
lecturer.salary)
def main():
"""This is where all the main user interaction should be"""
fname = raw_input("Enter filename: ")
for lecturer in (readfile(fname)):
lecturers.append(new_lecturer(lecturer))
print ""
answer = raw_input("Would you like to display lecturers by department(Y/N)?: ")
if answer == "Y":
print ""
department = raw_input("Please enter the department: ")
print ""
for lecturer in lecturers:
if lecturer.subject == department:
print_lecturer_detail(lecturer)
elif answer == "N":
# implement salary code here
pass
if __name__ == '__main__':
main()
This may be an overkill now, but it's better than dealing with lists in a long run. You'll see that dealing with properties become much simpler. You may want to improve each function further and make it more modular and reusable.
#Paul Morrington has the straight answer on the while part.
Here is the problem statement:
There is a record of 'n' students, each record having name of student, percent marks obtained in Maths, Physics and Chemistry. The user enters an integer 'n' followed by names and marks for the 'n' students. I am required to save the record in a dictionary data type. The user then enters name of a student and you are required to print the average percentage marks obtained by that student, correct to two decimal places.
what I have tried so far:
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['studentname', 'mathmarks', 'physicsmarks', 'chemistrymarks']
for i in range(0,num_students):
for entry in student_data:
student_info[entry] = raw_input(entry )
print student_info
print"please enter student name"
name = raw_input("student name")
if student_info['studentname'] == name:
print "Average student marks:", (int(student_info['mathmarks']) + int(student_info['physicsmarks']) + int(student_info['chemistrymarks']))/3
else:
print"please enter valid name"
This code is working is num_students = 1, However if num_students >1 the code fails.
I am unable to save the entry of each student in dictionary.
I am pretty new to python, would be glad if any one can help me with this.
Actually you need to create a nested dictionary with name as values and another dict as keys, in pretty way the nested dict may look like:
{
'anmol': {'chemistrymarks': 3, 'physicsmarks': 2, 'mathmarks': 1},
'uppal': {'chemistrymarks': 6, 'physicsmarks': 5, 'mathmarks': 4}
}
So you need to add the following lines to create a nested dictionary.
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['Math marks : ', 'Physics marks : ', 'Chemistry marks : ']
for i in range(0,num_students):
student_name = raw_input("Name :")
student_info[student_name] = {}
for entry in student_data:
student_info[student_name][entry] = int(raw_input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
#print student_info
print"Please enter student name ?"
name = raw_input("Student name : ")
if name in student_info.keys():
print "Average student marks : ", str(sum(student_info[name].values())/3.0)
else:
print"please enter valid name"
#youcan use print stmts. acording to your problem
n = raw_input()
grades = []
for entry in range(int(n)):
grades.append([i for i in raw_input().split()])
query = raw_input()
# Find list where first item matches name in query and
# assign grades to queryResult
queryResult = [x[1:] for x in grades if x[0] == query]
total = 0
scores = 0
for x in queryResult:
for y in x:
total += float(y)
scores += 1
print "%.2f" % (float(total/scores))
#Another way
num_of_student = int(raw_input())
dir_student = {}
for i in range(0,num_of_student):
student_info = raw_input()
name = student_info.split()
dir_student[name[0]] = [float(name[1]),float(name[2]),float(name[3])]
find_name = raw_input()
if dir_student.has_key(find_name):
print "{0:.2f}".format(sum(dir_student[find_name])/3.0)