Image to problem
The for loop works, though I can't figure out how to put the grade on a single line as shown in the photo. It asks for grades individualy when ran instead.
Here is my code:
num_students = int(input("Enter the number of students: "))
scores = []
for i in range(num_students):
scores.append(int(input("Enter a score: ")))
best_score = max(scores)
for i in range(num_students):
if scores[i] >= best_score - 10:
grade = "A"
elif scores[i] >= best_score - 20:
grade = "B"
elif scores[i] >= best_score - 30:
grade = "C"
elif scores[i] >= best_score - 40:
grade = "D"
else:
grade = "F"
print("Student", i, "score is", scores[i], "and grade is", grade)
Use a single input() call instead of a loop, and use .split() to get each individual score.
num_students = int(input("Enter the number of students: "))
scores = input(f"Enter {num_students} scores: ")
scores = [int(score) for score in scores.split()]
As John Gordon answered, your main issue is calling input inside a loop. That dictates that each user response will be on its own line. To fix this, call input once, then break the resulting string up using .split(). Split when called with no arguments will break a string into a list at each space.
Here is an example of how to do this (without the f strings and list comprehensions from John's answer):
num_students = int(input("Enter the number of students: "))
score_string = input("Enter " + str(num_students) + " scores: ")
scores = []
for score in score_string.split():
scores.append(int(score))
Related
I created a main() function and also 3 others and I am trying to get the other 3 to be executed into main()
I had it working then I messed it up at the very end, so I commented it out since it is not calling the 3 other functions.
# The program displays the letter grade and associated message for each exam score
# and the average exam score
# The program will not contain any repeated code and have a minimum of two functions besides Main.
def main():
# ask user to enter test scores
score = int(input("Enter your test scores separate by spaces, no commas: "))
# display test score
def showLetters(num, letterGrade):
print(f"{num:.1f} is an {letterGrade}\n")
# display score message
def examScores(num):
if 90 <= num <= 100:
letterGrade = "A"
print("Excellent Work")
elif 80 <= num <= 89:
letterGrade = "B"
print("Nice job")
elif 70 <= num <= 79:
letterGrade = "C"
print("Not bad")
elif 60 <= num <= 69:
letterGrade = "D"
print("Room for improvement")
else:
letterGrade = "F"
print("Go back and review")
return letterGrade
# calculate average of all scores entered by user
def calcAverages(grades):
numbers = scores.split()
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
print("Average exam score: ", sum(numbers) / len(numbers))
# ask user to repeat or quit
answer = str(input('Please enter "y" to run program again or "n" to exit: '))
if answer.lower() == 'n':
print('Thank you for using! Goodbye!')
sys.exit()
elif answer.lower() == 'y':
main()
# ??? = main()
# for n in ????? :
# showLetters(n, examScores(n, calcAverages(????)))
I made minor edits to your program and you now have the average values.
I have highlighted only the lines that need addition.
counter = 0 # tracks the number of times the function is called
#added the below 2 lines after counter
sumCredit = 0 #tracks the sum credit for all the students
sumStudyHrs = 0 #track the sum of the study hours for all the students
def myfunction():
global counter # tracks the number of times the function is called
#added two more global variables to keep track of the averages
global sumCredit #track the sum credit
global sumStudyHrs #track the sum study hours
the rest of the code can stay as is. Immediately after you print the student details, you need to accumulate the values so you can calculate the average.
print("Study hours: " + str(sumHours))
#added the below 2 lines after your print statements
sumCredit += classes
sumStudyHrs += sumHours
# Ask user if they want to end or restart
Now you need to use this information for your calculation.
When you print the average, use the above variables to compute the average.
print("Total Students: " + str(counter)) # tracks the number of times the function is called
#modified your average credits and average study with correct numerator
print("Average Credits: " + str(sumCredit / counter)) #computer average credits
print("Average Study Hours: " + str(sumStudyHrs / counter)) #compute average study hours
print('Thank you for using! Goodbye!')
This should give you the desired results.
Let me know if you need the full code.
I am a beginner programmer and am self learning python programming at home from a book. I am currently learning about strings. There is a question there which i solved it but I was thinking if there are other easier ways to solve it.
Q. A certain professor gives 100-point exams that are graded on the scale 90-100:A, 80-89:B, 70-79:C, 60-69:D, <60:F. Write a program that accepts an exam score as input and prints out the corresponding grade.
def main():
## making a list from 0-100
num = list(range(0,101))
## asking for the exam points
points = int(input("Enter the exam points 0-100: "))
## iterating num 0-60
for i in num[0:60]:
if i == points:
print("Your corresponding grade is F.")
## iterating num 60-70
for i in num[60:70]:
if i == points:
print("Your corresponding grade is D.")
## iterating num 70-80
for i in num[70:80]:
if i == points:
print("Your corresponding grade is C.")
## iterating num 80-90
for i in num[80:90]:
if i == points:
print("Your corresponding grade is B.")
## iterating num 90-100
for i in num[90:101]:
if i == points:
print("Your corresponding grade is A.")
main()
Yes, there is a much better way of writing that.
Given that you have an int, which is the score, all you have to do is compare it to the boundaries that determine the grade (using < or >).
points = int(input("Enter the exam points 0-100: "))
if points < 60:
grade = 'F'
elif points < 70:
grade = 'D'
elif points < 80:
grade = 'C'
elif points < 90:
grade = 'B'
else:
grade = 'A'
print("Your corresponding grade is", grade)
To make your code clearer, you can put the comparison logic into a function that returns the grade for a given score.
def calculate_grade(score):
if score < 60:
return 'F'
if score < 70:
return 'D'
if score < 80:
return 'C'
if score < 90:
return 'B'
return 'A'
def main():
points = int(input("Enter the exam points 0-100: "))
grade = calculate_grade(points)
print("Your corresponding grade is", grade)
There's still an easier and more concise way to do this. Try this:
points = int(input("Enter the exam points 0-100: "))
if 0 < points <= 60:
print "Your grade is F"
elif 60 < points <= 70:
print "Your grade is E"
elif 70 < points <= 80:
print "Your grade is D"
[and so on...]
Benefits are:
Plain comparisons instead of heavy linear search
No need to define any kind of dictionaries, methods or even classes or the like (especially since you mentioned you're not that experienced in Python by now)
Exits when it has found the right grade and doesn't evaluate further needless ifs
It is correct (gives the expected grade) and terribly inefficient:
you create an array when it could be avoided
you use linear search in arrays where simple comparisons would be enough
In addition you use a pure linear (unstructured) design.
You could:
make a function that converts points to grade
call it from a main that deals with input and output
Code example
def points_to_grade(points):
limits = [90, 80, 70, 60]
grades = ['A', 'B', 'C', 'D']
for i,limit in enumerate(limits):
if points >= limit:
return grade[i]
return 'F'
def main():
## asking for the exam points
points = int(input("Enter the exam points 0-100: "))
## convert to grade
grade = points_to_grade(points)
print("Your corresponding grade is {}.".format(grade))
#Maybe using dictionaries is more fun :)
marks = {'F':60, 'D':70,'C':80,'B':90}
points = int(input("Enter the exam points 0-100: "))
for key,value in marks.items():
if points<=value:
print("Your corresponding grade is ", key)
break
print("Your corresponding grade is A")
I do not code in python so I might not use right syntax but this is pretty much same in all languages. Iterating trough all values is bad practice. You just need few if statements (or switch/case), something like this:
if i<=100 and i>=90:
print("Grade is A")
if i<=89 and i>=80:
print("Grade is B")
etc....
def main():
points = int(input('Enter the exam points:'))
if points >= 90:
print('Your corresponding grade is A')
elif 80 <= points <= 90:
print('Your corresponding grade is B.')
elif 70 <= points <= 80:
print('Your corresponding grade is C.')
elif 60 <= points <= 70:
print('Your corresponding grade is D.')
elif 0 <= points <= 60:
print('Your corresponding grade is F.')
your solution is pretty not optimal and could be solved really nice using some basic logic, like below, which will perform better and would be more readable:
## asking for the exam points
point = int(input("Enter the exam points 0-100: "))
point_set = 'FEDCBA'
if point == 100:
print('A')
else:
print(point_set[point // 10 - 5])
code is using simple logic, once point is less than 60, 59 // 10 evaluates to 5 and 5 - 5 = 0, so grade at index 0 will be used - F. In case point is 100, this is some edge case, and that's why I'm using special if, for other cases there is simple math, which is self explanatory.
Yes there is, I would have used this approach
def main():
points = int(input("Enter the exam points 0-100: "))
if points >= 60:
print("Your corresponding grade is F.")
elif points > 60 and points < 70:
print("Your corresponding grade is D.")
elif points > 70 and points < 80:
print("Your corresponding grade is C.")
elif points > 80 and points < 90:
print("Your corresponding grade is B.")
elif points > 90:
print("Your corresponding grade is A.")
else:
print("Error: invalid value")
This question already has answers here:
Python 3- Assign grade
(2 answers)
Closed 6 years ago.
• Define a function to prompt the user to enter valid scores until they enter a sentinel value -999. Have this function both create and return a list of these scores. Do not store -999 in the list!
• Have main( ) then pass this the list to a second function which traverses the list of scores printing them along with their appropriate grade.
I am having trouble with the getGrade function, it gives the error for i in grades: name 'grades' is not defined.
def main():
grade = getScore()
print(getGrade(grade))
def getScore():
grades = []
score = int(input("Enter grades (-999 ends): "))
while score != -999:
grades.append(score)
score = int(input("Enter grades (-999 ends): "))
return grades
def getGrade(score):
best = 100
for i in grades:
if score >= best - 10:
print(" is an A")
elif score >= best - 20:
print(score, " is a B")
elif score >= best - 30:
print(score, " is a C")
elif score >= best - 40:
print(score, " is a D")
else:
print(score, "is a F")
main()
You defined your function to be getScore() but you're calling getScores(), so as would be expected this throws an error because the function you're calling doesn't actually exist / hasn't been defined.
Addendum: Since you changed your question, after fixing the previous error.
Likewise you're calling grades, but grades is defined in your other function not within the scope of the function where you're trying to iterate over grades.
I can't seem to figure this out - I want to get the average of all the inputs at the end of this program but I don't know how to save the inputs with each iteration of the loop. Any help would be much appreciated, thanks!
students = int(input("How many students are in your class?"))
while students <= 0:
print ("Invalid # of students. Try again.")
students = int(input("How many students are in your class?"))
studentnum = 1
for x in range (0, students):
print ("*** Student", studentnum, " ***")
score1 = int(input("Enter score for test #1"))
while score1 < 0:
print ("Invalid score. Try again.")
score1 = int(input("Enter score for test #1"))
score2 = int(input("Enter score for test #2"))
while score1 < 0:
print ("Invalid score. Try again.")
score1 = int(input("Enter score for test #1"))
part1 = score1 + score2
av = part1 / 2
print ("Average score for student #", studentnum, "is", av)
studentnum = studentnum + 1
# figure out how to average out all student inputs
Just create something to store them in outside your loop
scores = []
for x in range (0, students):
...
scores.append({'score1': score1, 'score2': score2, 'avg', av})
total_avg = sum(d['avg'] for d in scores) / len(scores)
You can build up a list of average scores for each student (by appending to it on each loop iteration), and then find the average of those after exiting the loop:
student_average_scores = []
for student in xrange(students):
# <your code that gets av>
student_average_scores.append(av)
average_score = sum(student_average_scores) / float(len(student_average_scores))
I have to write code that will calculate the average of three grades for each of a number of students, and display a message depending on the resulting average grades.
The program needs to be able process any number of students; but each student will have only 3 grades. I have to use a method to calculate the average score for each student, and also to determine the appropriate message depending on the average.
This is the code I have so far and I am stuck:
def main():
more = 'y'
while more == 'y' and more == 'Y':
numScore = int(input('How many test score per student: '))
for numtest in range(numScore):
print ("The score for test")
score = int(input(': '))
total += score
total = 0
print ("Student number", students + 1)
print ('-----------------------------------------')
avg = getAvg(numScore)
if avg > 90:
print ("You're doing excellent work")
elif avg > 85 and avg <= 90:
print("You are doing pretty good work")
elif avg > 70 and avg <= 85:
print ("You better get busy")
else:
print ("You need to get some help")
def getAvg (numScore):
avg = total / numScore
print ("The average for student number", student + 1, \ "is:", avg)
more = input('Do you want to enter another student test score and get the average score of the student (Enter y for yes and n for no): ')
main()
You had most of the elements correct in your script, but you need to think more about the order of everything.
Make sure you pass any arguments that are needed to a function. Your getAvg function needed three arguments for it to calculate the average and display it with the student number. Also you forgot to return average.
When calculating the avg ranges, if you first test for >90, then by definition the next elif avg > 85 will be less than or equal to 90 so it is only necessary to then test for >85.
The following has been rearranged a bit to work:
def getAvg(student, total, numScore):
average = total / numScore
print ("The average for student number", student, "is:", average)
return average
def main():
student = 0
more = 'y'
while more == 'y':
student += 1
total = 0
numScore = int(input('How many test scores per student: '))
for test_number in range(numScore):
print ("The score for test", test_number+1)
score = int(input(': '))
total += score
print ("Student number", student)
print ('-----------------------------------------')
avg = getAvg(student, total, numScore)
if avg > 90:
print ("You're doing excellent work")
elif avg > 85:
print("You are doing pretty good work")
elif avg > 70:
print ("You better get busy")
else:
print ("You need to get some help")
print()
print('Do you want to enter another student test score and get the average score of the student?')
more = input('Enter y for yes, and n for no: ').lower()
main()
Giving you the following kind of output:
How many test scores per student: 3
The score for test 1
: 93
The score for test 2
: 89
The score for test 3
: 73
Student number 1
-----------------------------------------
The average for student number 1 is: 85.0
You better get busy
Do you want to enter another student test score and get the average score of the student?
Enter y for yes, and n for no: n