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])
Related
Hi am new just started Computer Science at London Met we have programming in Python. In this code am trying to add items to already existing appended list list.append([student_name, student_age, student_sex]) from user input student_grade. How can i do this for each item in range. SO next time i print student_grade will be added to at the end of statement in form {each_item[3]} and 3 in the case will be student_grade ?
thanks in advance
from io import StringIO
import sys
number_student = int(input("How many students You want to add: "))
list = []
for i in range(0, number_student):
student_name = input("Whats Your name student? ")
student_age = input("Whats Your age student? ")
student_sex = input("Female or male? ")
list.append([student_name, student_age, student_sex])
comment withhash student_1 = (student_name, student_age + "years old", student_sex)
for each_item in list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}")
student_grade = input("Add student grade: ")
list.extend(["student_grade"])
#list.extend([student_grade])
for each_item in list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}, and your grades are", student_grade)
You shouldn't be adding student_grade to list, you should be adding it to each_item, the list for the current student.
Then when printing the grade, you use each_item[3] to get it.
Also, don't use list as a variable name, because it's a built-in function. I've renamed it to student_list below.
number_student = int(input("How many students You want to add: "))
student_list = []
for i in range(0, number_student):
student_name = input("Whats Your name student? ")
student_age = input("Whats Your age student? ")
student_sex = input("Female or male? ")
student_list.append([student_name, student_age, student_sex])
#student_1 = (student_name, student_age + "years old", student_sex)
for each_item in student_list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}")
student_grade = input("Add student grade: ")
each_item.append(student_grade)
for each_item in student_list:
print(f"Student name is {each_item[0]}, you are {each_item[1]} years old and you are {each_item[2]}, and your grades are {each_item[3]}")
I am kind of stuck, I am trying to make a function that allows me to append onto an empty dict, I want to add first name and surname, and also make it possible to have people with same last names but different first names. Any ideas? This is my first time asking a question on here, let me know if I need to find any other info thanks!
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
people[key] = input('Please enter your {}: '.format(value))
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
people()
First ask the user the input('Please enter your {}: '.format(value))
store it in a variable and then assign the people[key] to the variable
Example:
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people[key] = name
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
As mentioned in the comments that the people dicts gets reset
So with the approach of nested dicts you can use this:
def people():
people_ = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
print(qs)
index = f"person_{len(people_) + 1}"
people_[index] = {}
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people_[index][key] = name
print(people_)
prompt = input("Another person? (Y/N): ")
print(people_)
return people_
def people():
people = {}
add_person_msg = "Add person to list? (Y/N): "
first_name_msg = "First name: "
last_name_msg = "Last name: "
while input(add_person_msg).lower() == 'y': #.lower()
people[input(first_name_msg)] = input(last_name_msg)
return people
print(people())
if you wanted to work with the names before storing in dictionary, for example capitalize them:
def people_dict():
fn_msg = "First name: "
ln_msg = "Last name: "
people = {}
while input("Add person? y/n: ").lower() == 'y':
fn, ln = input(fn_msg).title(), input(ln_msg).title()
people[fn] = ln
return people
Also instead of using .format() method,
input('Please enter your {}: '.format(value)
if you are using Python 3.5 and above you can use f-strings:
input(f'Please enter your {value}:')
Im trying to print the email of the student, in the while loop at the bottom im also trying to input the students email but I cannot figure how to do it correctly.
Code:
array1 = []
numstudents = int(input("How many students are in the class?: "))
for i in range (numstudents):
studentname,studentemail,dayofbrith,monthofbrith,yearofbrith = input("Enter the student name, the
student's email and the date of birth in the form 'name, email, day of birth, month of birth, year
of birth' : ").split("")
array1.append(studentname+studentemail+dayofbrith+monthofbrith+yearofbrith)
if studentname == "stop":
print("")
break
else:
print("")
print(array1)
while True:
email = input("From which student's email you want: ")
if email any in array1[0]:
print("")
print(array1[1])
students = []
numstudents = int(input('How many students are in the class?: '))
for _ in range(numstudents):
print("Please enter the following: ")
print("The student's name, The student's email, day of birth, month of birth, year of birth")
students.append(input().split())
target = input("Which studen't email you want: ")
for i in students:
if i[0] == target:
print(f"The student's email is {i[1]}")
Try if this is what you want
Ah, definitely a problem for a dictionary.
dict1= {}
numstudents = int(input("How many students are in the class?: "))
for _ in range (numstudents): #As nk03 correctly points out - we don't need to carry the iterator, so can use an _ instead
studentname,studentemail,dayofbirth,monthofbirth,yearofbirth = input("Enter the student name, the student's email and the date of birth in the form 'name,email,day of birth,month of birth,year of birth' : ").split(",")
if studentname == "stop":
break
else:
dict1[studentname] = {'email':studentemail, 'dOB':dayofbirth, 'mOB':monthofbirth, 'yOB':yearofbirth}
while True:
name = input("From which student's email you want: ")
if name in dict1:
print(dict1[name]['email'])
else:
print(name + " not found in dict")
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!
Im new to python and I am currently working on a python script and want to add a loop at the end of it, currently the code is as follows:
#FinalGrade
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
Id like to find out if it would be possible to set a loop so another student can be entered, would this be possible?
Thank you
Why not put it in an infinite loop?
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
...
cont = input('Do you want to keep entering students? y/n: ')
Or if you want to keep all of the results:
results = []
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
...
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
...
cont = input('Do you want to keep entering students? y/n: ')
And you can just loop through the results to see them.
You mean just one more student to be entered?
You can probably do that with a while or for loop. Something along these lines:
counter = 0
while (counter < 2):
your existing code
....
counter += 1