grade=[]
names=[]
highest=0
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for numbers in range (1,number+1):
name=str(input('Enter name of student: '))
names.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
print('Case',case,'result')
print('name',list[list.index(max(grade))])
average=(sum(grade)/number)
print('average',average)
print('highest',max(grade))
print('name',names[grade.index(max(grade))])
I want to print name of the student with the highest mark. I have not learned anything other than list, while and for. NO dictionary ..nothing. I was wondering how can i do this?
ALSO i am getting this error!!! builtins.AttributeError: 'str' object has no attribute 'append'. HELP. thank you! :D
for number in range (1,number+1):
Don't reuse variable names for different things, call one of them numbers and the other number:
numbers=int(input('Enter number of students: '))
for number in range (1,numbers+1):
You made name a list in the beginning:
name=[]
but here you assign a single input to it:
name=str(input('Enter name of student: '))
The you append the new name to itself:
name.append(name)
which is not possible, because name is after the input no longer a list but a string. Again using different variable names for different things would help. Call the array names and the single input name:
names = []
#...
name=str(input('Enter name of student: '))
names.append(name)
And here:
print('name',list[list.index(max(grade))])
list is a build-in type, not one of your variables, so what you are trying to do is index a type, not a specific list. If you want to call index on a specific list you do so by using the variable name of that list. grade.index(...) will find the specific position matching the passed grade in grade and then you can use this position to get the corresponding name, because you know, that the name is at the same position in names:
print('name',names[grade.index(max(grade))])
Here is a somewhat more elaborated version; working through it should give you a better feel for the language.
from collections import namedtuple
import sys
# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
inp, rng = raw_input, xrange # Python 2.x
else:
inp, rng = input, range # Python 3.x
def type_getter(type):
"""
Build a function to prompt for input of required type
"""
def fn(prompt):
while True:
try:
return type(inp(prompt))
except ValueError:
pass # couldn't parse as the desired type - try again
fn.__doc__ = "\n Prompt for input and return as {}.\n".format(type.__name__)
return fn
get_int = type_getter(int)
get_float = type_getter(float)
# Student record datatype
Student = namedtuple('Student', ['name', 'mark'])
def get_students():
"""
Prompt for student names and marks;
return as list of Student
"""
students = []
while True:
name = inp("Enter name (or nothing to quit): ").strip()
if name:
mark = get_float("Enter {}'s mark: ".format(name))
students.append(Student(name, mark))
else:
return students
def main():
cases = get_int("How many cases are there? ")
for case in rng(1, cases+1):
print("\nCase {}:".format(case))
# get student data
students = get_students()
# perform calculations
avg = sum((student.mark for student in students), 0.) / len(students)
best_student = max(students, key=lambda x: x.mark)
# report the results
print(
"\nCase {} average was {:0.1f}%"
"\nBest student was {} with {:0.1f}%"
.format(case, avg, best_student.name, best_student.mark)
)
if __name__=="__main__":
main()
which runs like:
How many cases are there? 1
Case 1:
Enter name (or nothing to quit): A
Enter A's mark: 10.
Enter name (or nothing to quit): B
Enter B's mark: 20.
Enter name (or nothing to quit):
Case 1 average was 15.0%
Best student was B with 20.0%
Related
Prompt: Complete Creation (3.20)
Copy your solution from Creation (3.20) to here but delete the print statements (I PASTED THIS BELOW)
Make an empty list. The list will be used to store Student namedtuples
Add Kenneth and Maegan to the list
Create a funtion makeStudent(studentlist) where studentlist is your list of Student namedtuples
The function should do the following:
Take user input for each of the fields of the namedtuple
Create a Student namedtuple using the input
Add the Student to studentlist
Call makeStudent 3 times
Print student_list
Print Students whose list positions are odd in student_list
Hello! Can anyone help clarify what to do for step 5(Lab 3.2.1). The instructions are very ambiguous and unclear
Copy posted my code from 3.2.0
2.Deleted my print statements
3/4: #made an empty list and added "Kenneth" and "Maegan" to the list. Let me know if this is wrong and if the prompt is actually telling me to directly insert the names into the list.
student_list = list()
student_list.append('Kenneth')
student_list.append('Maegan')
Really confused about what to do. No hints were given either. I tried to do a def makeStudent(studentlist):
but was really confused about how I should write out the rest of the function. I experimented with doing a single line as well to gain all the inputs.
The function should do the following:
Take user input for each of the fields of the namedtuple (I tried doing it line by line input, and even one line)
Create a Student namedtuple using the input(How would I paste my input in the namedtuple? Same one as the one in code 3.20?)
Add the Student to studentlist(student_list.append(Student or 'Student'))
then I guess do that 3x. Use of return function.
print student_list
Then do List Sequence Slicing, I assume: lst[:] for example
My code is below
from collections import namedtuple
Student = namedtuple("Student", ["name","major","year","id","gpa"])
Student1 = Student("Kenneth", major="Computer Science", year=6, id=987654321, gpa=3.8)
Student2 = Student("Maegan", major="Neuroscience", year=4, id=123456789, gpa=3.4)
# make list
student_list = list()
student_list.append('Kenneth')
student_list.append('Maegan')
# add Kenneth and Maegan to the list
# make function
# print list / list with odd names
From what I understood, it's asking you to do the following. However, in the final part, I didn't see where it was asking for odd numbered names, so I just printed out the whole list.
from collections import namedtuple
Student = namedtuple("Student", ["name","major","year","id","gpa"])
Student1 = Student("Kenneth", major="Computer Science", year=6, id=987654321, gpa=3.8)
Student2 = Student("Maegan", major="Neuroscience", year=4, id=123456789, gpa=3.4)
# make list
student_list = list()
# add Kenneth and Maegan to the list
student_list.append(Student1)
student_list.append(Student2)
# make function
def makeStudent(studentlist):
name = input("Enter name: ")
major = input("Enter major: ")
year = input("Enter year: ")
id_ = input("Enter id: ")
gpa = input("Enter gpa: ")
new_student = Student(name, major=major, year=year, id=id_, gpa=gpa)
studentlist.append(new_student)
# call makeStudent 3 times
for _ in range(3):
makeStudent(student_list)
# print list
print(student_list)
When you run the script, if you enter the following values:
Enter name: John
Enter major: EE
Enter year: 1999
Enter id: 123
Enter gpa: 4
Enter name: Pete
Enter major: CS
Enter year: 2000
Enter id: 234
Enter gpa: 3
Enter name: Sam
Enter major: IE
Enter year: 2001
Enter id: 345
Enter gpa: 2
the final list would be printed out like so:
[Student(name='Kenneth', major='Computer Science', year=6, id=987654321, gpa=3.8),
Student(name='Maegan', major='Neuroscience', year=4, id=123456789, gpa=3.4),
Student(name='John', major='EE', year='1999', id='123', gpa='4'),
Student(name='Pete', major='CS', year='2000', id='234', gpa='3'),
Student(name='Sam', major='IE', year='2001', id='345', gpa='2')]
I have to make this program:
Write a program that allows a teacher to input how many students are in his/ her class, then allow them to enter in a name and mark for each student in the class using a for loop. Please note you do not need to record all of the names for later use, this is beyond the scope of the course * so just ask them each name, have it save the names over top of each other in ONE name variable.
i.e.)
INSIDE OF A LOOP
name = input (“Please enter student name: “)
Calculate the average mark for the entire class – this will require you to use totaling.
Output the class average at the end of the program, and ask if they would like to enter marks for another class. If they say yes, re-loop the program, if no, stop the program there.
So I started writing the program and it looks like this
studentamount = int(input("Please enter how many students are in your class: "))
for count in range():
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark"))
I ran into the following problem: how would I allow the set of code under the for loop to loop for each student? I was thinking I could just enter in the studentamount variable as the range but I can't since python does not allow you to enter in a variable as a range.
How would I get the for loop to loop for the amount of students typed in? e.g. if 20 students for student amount was typed in, I would want the for loop to loop 20 times. Your help and knowledge is much appreciated.
Read the user input, convert it to int and pass it as a parameter to range:
studentamount = input("Please enter how many students ...: ") # this is a str
studentamount = int(studentamount) # cast to int ...
for count in range(studentamount): # ... because that's what range expects
# ...
Python does not allow you to enter in a variable as a range.
Python does allow you to enter variables as a range, but they must be numbers. Input () reads input in as string, so you need to cast it.
So, this is correct:
```Python
studentamount = int(input("Please enter how many students are in your class: "))
for count in range(studentamount):
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark)
```
P.S a try - except clause would be useful here to catch people entering a non-integer data in [TypeError]
P.S.P.S #schwobaseggl 's example is good too, it is possibly more pythonistic to use the nested function studentamount = int(input("Text") than
studentamount = input("Text")
studentamount = int(studentamount)
You can store each student name and mark in a dictionary or tuple and store each dictionary (or tuple) into a list, see code sample (at the end enter "no" to exit or any other value to re-loop the program):
response = None
while response != 'no':
student_count = int(input('Please enter the number of students: '))
students = []
mark_sum = 0
print('There are {} student(s).'.format(student_count))
for student_index in range(student_count):
student_order = student_index + 1
student_name = input('Please enter the name of student number {}: '.format(student_order))
student_mark = float(input('Please enter the mark of student number {}: '.format(student_order)))
students.append({'name': student_name, 'mark': student_mark})
mark_sum += student_mark
print('The average mark for {} student(s) is: {}'.format(student_count, mark_sum / student_count))
response = input('Do you want to enter marks for another class [yes][no]: ')
I am writing a program for my intro CS class but I am a little stuck.
I have a designated list of names that correspond to a list of scores.
I am supposed to prompt the user to enter a name and then the program is supposed to output the name that was entered along with the corresponding score.
As I have it written now the program is printing the first name and score in the set regardless of the input. I have been stuck on this for a while, any help would be greatly appreciated!
Here is what I have right now:
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan'];
scores=['88','92','95','84','85','92','89'];
input("Please enter student's name:")
for i in range (0,7):
print (input(names[i] + scores[i]));
the program is supposed to output the name that was entered
That'll be hard considering you aren't capturing the input() return value.
Try this (as an example)
name = input("Please enter student's name:")
print(name)
Then, you next task is to check (in your loop) when name == <a name in the list>
Hint: You can use these for your loop rather than range(0,7)
for student in names:
or, even better, see zip lists in python
for (student, score) in zip(names, scores):
Using the zip function, you can combine the two lists together in an easy to use 1-to-1 group of tuples.
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan']
scores=['88','92','95','84','85','92','89']
data = zip(names, scores) # <- ('Jim', '88'), ('Sarah', '92'), ...
stud = input('Enter the student's name: ')
for (student, score) in data:
if (stud == student):
print('{} -> {}'.format(student, score))
Better to use Python dictionaries for that:
student_scores = {'Jim': 88, 'Sarah': 92, 'Jason': 95}
and so on...
Then you can call for each of them like so;
name = input("Please enter student's name: ")
print(name + 'has a score of ' + student_scores[name])
I am trying to create an attendance logger where I create a dictionary which I fill with student names. The names will be lists where I append their class attendance data (whether they attended class or not). The code I have so far is displayed below`
#! /bin/python3
#add student to dict
def add_student(_dict):
student=input('Add student :')
_dict[student]=[]
return _dict
#collect outcomes
def collector(student,_dict, outcome):
_dict[student].append(outcome)
return _dict
#counts target
def count(_dict,target):
for i in _dict:
# records total attendance names
attendance_stat = len(_dict[i])
# records total instances absent
freq_of_absence=_dict[i].count(target)
# records percentage of absence
perc_absence = float((freq_of_absence/attendance_stat)*100)
print(i,'DAYS ABSENT =',freq_of_absence)
print('TOTAL DAYS: ', i, attendance_stat)
print('PERCENTAGE OF ABSENCE:', i, str(round(perc_absence, 2))+'%')
#main function
def main():
#date=input('DATE: ')
outcomes=['Y','N']
student_names = {}
try:
totalstudents = int(input('NO. OF STUDENTS: '))
except ValueError:
print('input an integer')
totalstudents = int(input('NO. OF STUDENTS: '))
while len(student_names) < totalstudents:
add_student(student_names)
print(student_names)
i = 0
while i < totalstudents:
i = i + 1
target='Y'
student=str(input('student :'))
outcome=str(input('outcome :'))
collector(student,student_names,outcome)
count(student_names,target)
if __name__=='__main__':
main()
`
The code works well so far but the problem is when the number of students is too large, time taken to input is extensive cutting in on class time. Since the number of absentees is usually less than those present, is it possible to select from the dictionary students absent which will append the value Y for each selected absent, while appending N to the remaining lists in dictionary.
This isn't exactly what you're asking for, but I think it will help. Instead of asking the user to input a name each time for the second part, why not just print the name yourself, and only ask for the outcome? Your last while loop would then become a for loop instead, like this:
for student_name in student_names:
outcome = input("Outcome for {}: ".format(sudent_name))
collector(student_name, student_names, outcome)
You could also add some logic to check if outcome is an empty string, and if so, set it to 'N'. This would just allow you to hit enter for most of the names, and only have to type in 'Y' for the certain ones that are absent. That would look like this:
for student_name in student_names:
outcome = input("Outcome for {}: ".format(sudent_name))
if outcome = "":
outcome = "N"
collector(student_name, student_names, outcome)
I'm a Python beginner trying write a program that will allow the user to input individuals names and test scores and I am supposed to give back a grade after finding the average so far I've been able to write the program but I am experiencing difficulties trying to debug it.
my programs works fine until it starts to calculate the average, it usually displays an error message saying
"TypeError: 'float' object is not subscriptable"
Could somebody please help me why my codes are not working? Thank you for your help in advance!
def calcaverage(test1,test2,test3):
for count in range(numofstudent):
curraverage=((test1[count]+ test2[count]+ test3[count])/3)
if curraverage>= 90:
grade= "A"
return grade
else:
if curraverage >= 80 and curraverage < 90:
grade= "B"
return grade
else:
if curraverage >= 70 and curraverage < 80:
grade= "C"
return grade
else:
if curraverage < 70:
grade= "F"
return grade
numofstudent=int(input("How Many Students?: "))
students=[]
test1=[]
test2=[]
test3=[]
averagescore=[]
grade=[]
for count in range(numofstudent):
currstudent=input("Please enter name of student: ")
students.append(currstudent)
currstudenttest1= float(input("First test score?: "))
currstudenttest2= float(input("Second test score?: "))
currstudenttest3= float(input("Third test score?: "))
test1.append(currstudenttest1)
test2.append(currstudenttest2)
test3.append(currstudenttest3)
grade=calcaverage(test1,test2,test3)
averagescore.append(grade)
print([students], "your grade is " ,[grade])
Here comes some tough love.
There are multiple problems here. In general you need to learn to think through your program line by line, as though you were the CPU, and figure out what you want to happen at each step. Then you need to weed out mistakes until what the actual CPU does is equal to what you want.
In the second line (the for loop), the variable "curraverage" is undefined since it doesn't get defined until a couple lines later. It's the wrong variable anyway; you want to loop over all the students so you need range(numofstudent).
In the next line, "test" is undefined. You meant "test3." If you want to learn to program you just cannot allow yourself to make these kinds of mistakes.
The variable curraverge looks like a typo, but it's actually not. Think of a better name, it's not hard.
In line 5, averagescore (which was declared as a global down below, and was a list) is now re-declared as a local and bound to a float. As such you cannot append to it in line 6. Line 5 should simply be discarded, it does nothing except create a bug.
The line grade[count] doesn't do anything. You need to call grade.append to build the list of grades. But since you haven't computed the grade yet, no such line belongs here.
Next you compare averagescore to 90 and 80 and so forth, but that's the wrong variable again. That's the list you declared below. Here you want the score for one student (which is curraverage).
Then you return from inside the loop, causing the function to exit before you have computed more than one grade. None of those returns should be in there.
I could go on. You need to be much, much more careful about what you are doing. Keep in mind that computers are profoundly stupid - they do exactly what they're told, whether that's what you want them to do or not.
Best of luck to you.
Here is a working example which uses some more advanced ideas:
we split the code into functions; each function does one specific thing. This makes the code much easier to think about, test, debug, and reuse.
each function has a docstring - built-in documentation about what it does and how to use it, which can be reviewed with Python's help() function, ie help(average).
we define a Student class which stores the name and marks for a single student. It knows how to create a student by prompting for input, and how to calculate an overall grade from the marks.
marks are entered using a list comprehension; something like
result = [func(x) for x in lst]
which is an easier-to-read equivalent of
result = []
for x in lst:
result.append(func(x))
Here's the code; if you trace through it and understand it, it should help:
# assumes Python 3
def get_int(prompt):
"""
Prompt the user to enter a number;
return the number as an int
"""
while True:
try:
return int(input(prompt))
except ValueError: # couldn't parse as int
pass # skip the error message
def average(lst):
"""
Return the average of a list of numbers
"""
return sum(lst) / len(lst)
def grade(mark):
"""
Given a mark as a percentage,
return a grade letter
"""
if mark >= 90.:
return "A"
elif mark >= 80.:
return "B"
elif mark >= 70.:
return "C"
else:
return "F"
class Student:
#classmethod
def from_prompt(cls):
"""
Prompt for a student's information,
return it as a Student object
"""
name = input("Please enter student name: ")
marks = [float(f) for f in input("Please enter {}'s marks: ".format(name)).split()]
return cls(name, marks) # implicitly calls __init__
def __init__(self, name, marks):
self.name = name
self.marks = marks
def grade(self):
"""
Return the student's overall grade
"""
return grade(average(self.marks))
def main():
# get student data
num_students = get_int("How many students do you want to enter? ")
print("")
students = [Student.from_prompt() for _ in range(num_students)]
# print student grades
print("")
for student in students:
print("{}'s grade is {}".format(student.name, student.grade()))
if __name__=="__main__":
# if loaded as a program, call the main function
main()
and runs like
How many students do you want to enter? 4
Please enter student name: Anna
Please enter Anna's marks: 91.0 94.5 96.1
Please enter student name: Ben
Please enter Ben's marks: 82 86 90
Please enter student name: Charlie
Please enter Charlie's marks: 65 75 85
Please enter student name: Farquad
Please enter Farquad's marks: 10 40 55 36 51 16
Anna's grade is A
Ben's grade is B
Charlie's grade is C
Farquad's grade is F