I am trying to let a user keep entering module and grades and store it as a dictionary {module:grades} and store this dictionary in a list.
I have 3 issues in this.
I am unable to use F6 in the second raw_input which is F7.
Secondly, I am using 'done' to stop the loop. When I print the information it looks like this:
{done : 100}
{done : 80}
and so on.. So the module name keeps getting replaced by the word 'done'.
And lastly I am trying to make the print out appear as follows: (which is not hapening now..)
Grades: Computer Science: 100
Computer Graphics: 80
I have finished the rest of my work less this portion which I am stuck with. Any assistance is deeply appreciated. Thank you so much.
students = []
class Student:
grades = {}
def setGrades(self, grades):
self.grades = grades
def addStudent():
while F6 != 'done':
F6 = raw_input("Please enter module name. type 'done' to quit: ")
if F6 == 'done':
break
F7 = raw_input("Please enter the grades for " ,F6, ':')
student.setGrades({F6:F7})
For starters, your code (as is) should look something like this
students = []
class Student:
grades = {}
def setGrades(self, grades):
self.grades = grades
def addStudent():
while True:
F6 = raw_input("Please enter module name. type 'done' to quit: ")
if F6 == 'done':
break
F7 = raw_input("Please enter the grades for " ,F6, ':')
student.setGrades({F6:F7})
In my opinion you should also have a better api for setting Grades. Something like this would suffice imo:
def set_grades(self, lesson, grade):
self.grades[lesson] = grade
Finally in order to print the grades you should have a method like this:
def print_grades(self):
for lesson, grade in grades.items():
print lesson, grade
Last but not least in your raw input, in order to use F6 you have to do something like that:
F7 = raw_input("Please enter the grades for %s: " % F6)
To sum it all up, if I were you my code would look something like this:
class Student:
grades = {}
def set_grades(self, lesson, grade):
self.grades[lesson] = grade
def addStudent():
while True:
F6 = raw_input("Please enter module name. type 'done' to quit: ")
if F6 == 'done':
break
F7 = raw_input("Please enter the grades for %s: " % F6)
student.setGrades(F6, F7)
def print_grades(self):
for lesson, grade in grades.items():
print lesson, grade
Related
I try to create a simple program for tracking students scores. This is my code, but I have no idea how to track students scores. Almost of the students are unknown and will always be different.
I am trying to detect wether the students' score is equal to 10.
name_list = []
enter_name = True
while enter_name:
name = input("Name: ")
name_list.append(name)
if name == "end":
enter_name = False
name_list = name_list[:-1]
#score = 0
#for word in name_list:
#score = int(input(f"{word} = {score}"))
#I am not sure about the last part, i think i turned to wrong direction
You should be using a dictionary keyed on student name. Values should be the student's score as an integer (because you want to compare against a constant value of 10).
As you're going to want integer input from the user, you'll need to validate it in order to avoid unwanted exceptions.
Consider this:
DB = {}
while (name := input('Enter student name: ')) != 'end':
while True:
try:
DB[name] = int(input(f'Enter score for {name}: '))
break
except ValueError:
print('Score should be an integer')
for k, v in DB.items():
print(f'{k} {"Genius" if v >= 10 else v}')
Sample:
Enter student name: Fred
Enter score for Fred: abc
Score should be an integer
Enter score for Fred: 10
Enter student name: Mick
Enter score for Mick: 5
Enter student name: end
Fred Genius
Mick 5
You should use a python dictionary:
students_scores = {}
while True:
name = input("Name: ")
if name == "end":
break
score = int(input("Score: "))
students_scores[name] = score
If you want to know whether a student has a score of 10, you can use if students_scores[student] == 10:.
I need help with a python file to make a simple Grade Book print properly. I've gotten it to print but its not doing exactly what I need it to. The print results look like this,
{'Fred': '99', 'Fred2': '99', ...}
Ideally I'd like it to print just the name and grade next to each other, on a new line for each name / grade. Something like this:
"Name: Fred | Grade: 99"
I have to use a list / dictionary and need the while loop
Here is the best solution I have tried thus far:
student_grades = {}
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()
while entries == "y":
name = input('Enter a students name: ')
grade = input('Enter the student\'s grade: ')
#Put in dictionary
student_grades[name] = grade
#Print
print(student_grades)
entries = input('Would you like to enter a students name and grade? (Y/N)')
entries = entries.lower()
else:
names = list(student_grades.keys())
grades = list(student_grades.values())
print()
print(' Grade Book ')
print('--------------------')
print(student_grades)
for student,grade in student_grades.iteritems():
print "Name:%s, Grade:%s"%(student,grade)
This is the Final Working code for anyone who may need it in the future! Thanks to all who helped!
student_grades = {}
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()
while entries == "y":
name = input('Enter a students name: ')
grade = input('Enter the student\'s grade: ')
#Put in dictionary
student_grades[name] = grade
#Print
print(student_grades)
entries = input('Would you like to enter a students name and grade? (Y/N): ')
entries = entries.lower()
else:
names = list(student_grades.keys())
grades = list(student_grades.values())
print()
print(' Grade Book ')
print('--------------------')
print()
for name in student_grades:
print("Name: "+name+" "+"Grade: "+student_grades[name])
I am now learning functions in python. I came across an exercise that asks me to write a script that will tell the user that the student is in a class or not. Here is the result that the script should present:
Welcome to the student checker!
Please give me the name of a student (enter 'q' to quit): [student1]
No, that student is not in the class.
Please give me the name of a student (enter 'q' to quit): [student2]
Yes, that student is enrolled in the class!
Please give me the name of a student (enter 'q' to quit): q
Goodbye!
I have written a script that fulfills the requirements. Here is the script:
print "Welcome to the student checker!"
students = ['Andreas', 'Martina', 'Maria']
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
if name_student in students:
print "Yes, {} is enrolled in the class!".format(name_student)
elif name_student not in students:
print "No, {} is not in the class.".format(name_student)
But the exercise states that there should be a function that returns True if the student is present, and False if not.
Could anybody enlighten me on how can I change my script to fulfill the requirement of adding a function that returns True if the student is present, and False if not?
Thanks in advance!! Peace!!!
Try doing something like this:
print "Welcome to the student checker!"
students = ['Andreas', 'Martina', 'Maria']
def is_present(name_student):
if name_student in students:
print "Yes, {} is enrolled in the class!".format(name_student)
return True
elif name_student not in students:
print "No, {} is not in the class.".format(name_student)
return False
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
is_present(name_student)
Wrap the logic into a function, so it can return a value, and call it each time your infinite loop iterates.
#edit
#barak manos is right, I updated the code
The following is one way to convert the student test into a function:
def student_present(student):
return student in ['Andreas', 'Martina', 'Maria']
print "Welcome to the student checker!"
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
if student_present(name_student):
print "Yes, {} is enrolled in the class!".format(name_student)
else:
print "No, {} is not in the class.".format(name_student)
Note student in [xxxxxx] automatically gives you a boolean result which can be returned directly. There is no need to explicitly return True and False.
Another point to consider, what happens if martina is entered? Using the current code it would state not in class. If you changed the function as follows, it would also accept this:
def student_present(student):
return student.lower() in ['andreas', 'martina', 'maria']
python 3.3.3
I am trying to write a program for class and I am lost. Here is what I need to do.
I need to calculate an average per student based on grades entered.
I need to calculate a class average.
if a student enters a grade of -1 input of grades stop.
need to print a message with each students grade.
the students grade should show a numeric grade and a letter grade.
the message will be based off of the students letter grade.
how do i collect and store students name and test grades.
so that i can output it all at once to where it will show the students name.
thier numeric average, a letter grade based off that average,
and a statement based off the letter grade they recieved?
heres the code i have so far:
def main():
another_student = 'y'
while another_student == 'y' or another_student == 'Y':
student_average()
print()
another_student = input('do you have another student to enter (y/n) ? ')
while another_student == 'n' or another_student == 'N':
student_average_list()
class_average()
break
def student_average():
total = 0.0
print()
student_name = input('what is the students name? ')
print()
print()
print(student_name)
print('-------------------')
number_of_tests = int(input('please enter the number of tests : '))
for test_num in range(number_of_tests):
print('test number', test_num + 1, end='')
score = float(input(': '))
total += score
student_average = total / number_of_tests
print ()
print(student_name,"'s average is : ",student_average, sep='')
def student_average_list():
print ('kahdjskh')
def class_average():
print ('alsjd')
main()
I think this is close to what you're basically looking for. It defines aStudentclass to make data storage and processing a little easier to manage.
class Student(object):
def __init__(self, name):
self.name, self.grades = name, []
def append_grade(self, grade):
self.grades.append(grade)
def average(self):
return sum(self.grades) / len(self.grades)
def letter_grade(self):
average = self.average()
for value, grade in (90, "A"), (80, "B"), (70, "C"), (60, "D"):
if average >= value:
return grade
else:
return "F"
def main():
print()
print('Collecting class student information')
a_class = [] # "class" by itself is a reserved word in Python, avoid using
while True:
print()
print('{} students in class so far'.format(len(a_class)))
another_student = input('Do you have another student to enter (y/n) ? ')
if another_student[0].lower() != 'y':
break
print()
student_name = input('What is the student\'s name? ')
a_class.append(Student(student_name))
print()
print('student :', student_name)
print('-------------------')
number_of_tests = int(input('Please enter the number of tests : '))
for test_num in range(1, number_of_tests+1):
print('test number {}'.format(test_num), end='')
score = float(input(' : '))
if score < 0: # stop early?
break
a_class[-1].append_grade(score) # append to last student added
print_report(a_class)
def print_report(a_class):
print()
print('Class Report')
print()
for student in sorted(a_class, key=lambda s: s.name):
print('student: {:20s} average test score: {:3.2f} grade: {}'.format(
student.name, student.average(), student.letter_grade()))
print()
print('The class average is {:.2f}'.format(class_average(a_class)))
def class_average(a_class):
return sum(student.average() for student in a_class) / len(a_class)
main()
You need to keep a list of marks for the whole class. student_average function is doing too many things. Maybe make a function get_student_marks that just returns the list of a student's marks. You'd need an average function to compute the average of a list, which you could use for both student average and class average. Good luck!
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.