Menu driven program - python

I'm trying to complete my menu driven program; however, I can't get this code to function properly. the goal is to get information from my previous code then get the evaluated output here. It keeps asking to execute my previous function before the menu pops up. get_list is the previous function that gets the list of numbers from the user.
previous code
def get_list(score_list=None):
if score_list is None:
score_list = []
n = int(input('How many scores do you want to enter? '))
for n in range(1, n + 1):
score = float(input('Enter score #{}: '.format(n)))
while True:
if 0 > score or score > 100:
print('Invalid score entered!!\n', 'Score should be a value between 0 and 100')
score = float(input('Enter score #{}: '.format(n)))
continue
else:
score_list.append(score)
break
return score_list
pass
problem code
def evaluate_list():
score_list = get_list()
lowest_score = min(score_list)
score_list.remove(lowest_score)
score_average = sum(score_list) / len(score_list)
if 90 < score_average <= 100:
grade = 'A'
elif 70 < score_average <= 80:
grade = 'B'
elif 40 < score_average <= 60:
grade = 'C'
elif score_average > 20 and score_average >= 40:
grade = 'D'
else:
grade = 'F'
print('----------Results--------------')
print('Lowest Score : ', lowest_score)
print('Modified List: ', score_list)
print('score Average: ', f'{score_average:.2f}')
print('Grade : ', grade)
evaluate_list()

Related

Letter for Grade for multiple students

def getGradeInfo():
numStudent = int(input('Total number of students: '))
getGrades = input(f'Enter {numStudent} scores: ')
gradeListNum = getGrades.split(' ')
maxScore = int(max(gradeListNum[0:numStudent]))
gradeListLetter = []
for grade in gradeListLetter:
if int(grade) >= maxScore - 10:
gradeListLetter.append('A')
elif int(grade) >= maxScore - 20:
gradeListLetter.append('B')
elif int(grade) >= maxScore - 30:
gradeListLetter.append('C')
elif int(grade) >= maxScore - 40:
gradeListLetter.append('D')
else:
gradeListLetter.append('F')
a = 1
while a<= numStudent:
print(f'Student{a} score is {gradeListNum[a-1]} and grade is')
a+=1
getGradeInfo()
I can get the input for the number of students in the code but can't figure out how to assign the letter to each of the student's grades for the print statement
As Adam Oppenheimer said,
for grade in gradeListLetter:
should be
for grade in gradeListNum:
Also,
print(f'Student{a} score is {gradeListNum[a-1]} and grade is')
should be
print(f'Student {a}: score is {gradeListNum[a - 1]} and grade is {gradeListLetter[a - 1]}')
You are iterating over gradeListLetter which is empty, try iterating over gradeListNum instead.
You also aren't printing the letter grade in your print statement.

Writing text and intergers to a file, then reading from the file to calculate grade averages

This is what I am trying to display. These are the by products of 2 functions.
The first paragraph is the create() function which creates the "grades.txt" file. I think I got down pretty easily.
Secondly, the next paragraph is from the "Retrieve()" function reading from the "grades.txt" file and displaying the class name and GPA then calculating average for those classes and displaying them.
I feel like Im right at the cusp but im stuck as to where to go from here because im plagued with "STRG" errors.
> def main ():
> create()
> retrieve()
>
> def create():
> outfile = open('grades.txt', 'w')
> count_files = 0
>
> #Gather class name or press 'Enter' to quit
> class_or_exit = input('Enter course name or Enter to quit: ')
>
> #Create While loop if 'Enter' is pressed exit and close file
> while class_or_exit !="":
> count_files += 1
> grade =(input('Enter grade (interger) achieved: '))
> class_or_exit = input('Enter course name or Enter to quit: ')
>
>
>
> #Write info to the file
> outfile.write(str(class_or_exit) + '\n')
> outfile.write(str(grade) + '\n')
>
> #Close file
> outfile.close()
> print('File was created and closed')
> return grade, class_or_exit
>
> def retrieve():
> print('Here is your GPA for the classes you entered:')
> outfile = open('grades.txt', 'r')
> total = 0.0
> count = 0
> class_or_exit = outfile.readline()
> grade = float(outfile.readline())
>
> if grade >= 90:
> grade = 4.0
> count = count + 1
> print(f"{class_or_exit:} class" + str + "{grade:.2f}")
> elif grade >= 80:
> grade = 3.0
> count = count + 1
> print(f'{class_or_exit:} class'+ str + "{grade:.2f}")
> elif grade >= 80:
> grade = 2.0
> count = count + 1
> print(f'{class_or_exit:} class'+ str + "{grade:.2f}")
> elif grade >= 80:
> grade = 1.0
> count = count + 1
> print(f'{class_or_exit:} class'+ str + "{grade:.2f}")
>
> main()
This does what I think you meant to do. Note carefully the differences between this and what you wrote.
def create():
outfile = open('grades.txt', 'w')
#Gather class name or press 'Enter' to quit
class_or_exit = input('Enter course name or Enter to quit: ')
#Create While loop if 'Enter' is pressed exit and close file
while class_or_exit !="":
grade =(input('Enter grade (interger) achieved: '))
#Write info to the file
outfile.write(class_or_exit + '\n')
outfile.write(grade + '\n')
class_or_exit = input('Enter course name or Enter to quit: ')
#Close file
outfile.close()
print('File was created and closed')
return grade, class_or_exit
def retrieve():
print('Here is your GPA for the classes you entered:')
outfile = open('grades.txt', 'r')
total = 0.0
count = 0
while True:
class_or_exit = outfile.readline()
if not class_or_exit:
break
grade = float(outfile.readline())
count += 1
if grade >= 90:
total += 4.0
elif grade >= 80:
total += 3.0
elif grade >= 70:
total += 2.0
elif grade >= 60:
total += 1.0
print("Your GPA is", total/count)
def main ():
create()
retrieve()
main()

python: grading assignment, negative value

I am working on a python lettering assignment.
90 or above is an A and so on and so on for the rest of the letter grades; but when a value is inputted as a negative number, I need the code to do nothing other than display an error.
This is what i tried so far:
#Design a Python program to assign grade to 10 students
#For each student, the program first asks for the user to enter a positive number
#A if the score is greater than or equal to 90
#B if the score is greater than or equal to 80 but less than 90
#C if the score is greater than or equal to 70 but less than 80
#D if the score is greater than or equal to 60 but less than 70
#F is the score is less than 60
#Ihen the program dispalys the letter grade for this student.
#Use while loop to repeat the above grade process for 10 students.
keep_going = 'y'
while keep_going == "y":
num = float(input("Enter a number: "))
if num >= 90:
print("You have an A")
elif num >= 80:
print("You have an 3")
elif num >= 70:
print("You have an C")
elif num >= 60:
print("You have an D")
elif (num < 60 and <= 0:
print ("You have an F")
else:
print("lnvalid Test Score.")
Original screenshot
I see three problems, all in the same line:
elif (num < 60 and <= 0:
Syntax: num < 60 and <= 0 is not a valid expression; should be num < 60 and num <= 0
Logic: num <= 0 is not what you want, it should be num >= 0
Syntax: you missed a closing bracket ).
If you change those, it should work.
grade = int(input("Enter Score:"))
print "FFFFFDCBAA"[grade//10] if grade >= 0 else "ERROR!!!!"
you just have to change your elif for below 60.
keep_going = 'y'
while keep_going == "y":
num = float(input("Enter a number: "))
if num >= 90:
print("You have an A")
elif num >= 80:
print("You have an 3")
elif num >= 70:
print("You have an C")
elif num >= 60:
print("You have an D")
elif 60 > num >= 0:
print ("You have an F")
else:
print("lnvalid Test Score.")

how do I use a list as an argument in a function using python

I'm fairly new to programming and have only been doing so for a month. Currently I'm trying to get user input, store it in a list, and pass that list into a function. I'm having trouble using the list as an argument for my function (the last line of code). Thank in advance!
grade_list = []
percentages = 0
while True:
percentages = input("Enter some numbers here: ")
if percentages == "done":
break
grade_list.append(percentages)
print(grade_list)
def gpaCalc(marks):
gpaList = []
for grade in marks: #sorts data
if grade <= 49.99:
grade = 0.00
elif 50 <= grade <= 52.99:
grade = 0.70
elif 53 <= grade <= 56.99:
grade = 1.00
elif 57 <= grade <= 59.99:
grade = 1.30
elif 60 <= grade <= 62.99:
grade = 1.70
elif 63 <= grade <= 66.99:
grade = 2.00
elif 67 <= grade <= 69.99:
grade = 2.30
elif 70 <= grade <= 72.99:
grade = 2.70
elif 73 <= grade <= 76.99:
grade = 3.00
elif 77 <= grade <= 79.99:
grade = 3.30
elif 80 <= grade <= 84.99:
grade = 3.70
elif 85 <= grade <= 89.99:
grade = 3.90
elif 90 <= grade <= 100:
grade = 4.00
gpaList.append(grade) #gathers data into list
gpaList.sort()
return gpaList
print (gpaCalc(PROBLEM))
You can pass a list as you would pass it normally into any function, just always make sure you are accessing the items in the list by indexing correctly, rather than calculating the whole list. Use the following instead:
def gpaCalc(marks):
gpaList = []
for grade in marks[0]: #sorts data
if grade <= 49.99:
grade = 0.00
elif 50 <= grade <= 52.99:
grade = 0.70
elif 53 <= grade <= 56.99:
grade = 1.00
elif 57 <= grade <= 59.99:
grade = 1.30
elif 60 <= grade <= 62.99:
grade = 1.70
elif 63 <= grade <= 66.99:
grade = 2.00
elif 67 <= grade <= 69.99:
grade = 2.30
elif 70 <= grade <= 72.99:
grade = 2.70
elif 73 <= grade <= 76.99:
grade = 3.00
elif 77 <= grade <= 79.99:
grade = 3.30
elif 80 <= grade <= 84.99:
grade = 3.70
elif 85 <= grade <= 89.99:
grade = 3.90
elif 90 <= grade <= 100:
grade = 4.00
gpaList.append(grade) #gathers data into list
gpaList.sort()
return gpaList
grade_list = []
percentages = 0
while True:
percentages = input("Enter some numbers here: ")
if percentages == "done":
break
grade_list.append(percentages)
print(gpaCalc(grade_list))
keep your check for "done" as is. if it is not done, then convert float.
while True:
percentages = input("Enter some numbers here and 'done' to exit:")
if percentages == "done":
break
try:
grade_list.append(float(percentages))
except ValueError:
pass
sorting...
for grade in marks: #sorts data
.....
gpaList.append(grade) #gathers data into list
#also, sort outside the loop, when done, not each time.
gpaList.sort()
return gpaList
Right before the last print line, define your list of marks, e.g. marks = [70, 68, 50, 89, ...] and pass it to gpaCalc in your function call:
print(gpaCalc(marks))
Note that Python convention says you should not use camel case in your identifiers; use underlines instead: gpa_calc
Edit: I missed the point of the question! To get the user's inputs, use a loop:
def get_user_input():
grades = []
while True:
# take input
value = ... # figure it out
if value == 'q':
break
try:
# do basic validation here
grades.append(int(value))
# might be a good idea to check the range too…
except ValueError:
print("This is not a valid grade!")
return grades
If you would like an explanation, leave a comment!

Not understanding my python dilemma

I am trying to finish up an assignment for a class "grade determination"
Write a program that will input 3 test scores.The program should determine and display their average.The program should then display the appropriate letter grade based on the average.The letter grade should be determined using a standard 10-point scale: (A = 90-100; B = 80-89.999; C = 70-79.999, etc.)
So far what I've been able to put together, (and it works averaging)
def main():
score1 = input("What is the first test score? ")
score2 = input("What is the second test score? ")
score3 = input("What is the third test score? ")
scoreaverage = score1 + score2 + score3
score = (scoreaverage / 3)
if score < 60:
grade="F"
elif score < 70:
grade="C"
elif score < 80:
grade="B"
elif score < 90:
grade="A"
else:
print score, " is the student's grade average!"
main()
If I replace score with grade I get an error.
raceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 16, in main
UnboundLocalError: local variable 'grade' referenced before assignment
So my question is how do I get the letter grade to print correctly?
def main():
score1 = input("What is the first test score? ")
score2 = input("What is the second test score? ")
score3 = input("What is the third test score? ")
scoreaverage = score1 + score2 + score3
score = (scoreaverage / 3)
if score < 60:
grade="F"
elif score < 70:
grade="C"
elif score < 80:
grade="B"
elif score < 90:
grade="A"
else:
print score, " is the student's grade average!"
main()
This would be your indented code. Are you sure you get the error you are mentioning?
The following code would generate the error you are mentioning.
print grade, " is the student's grade average!"
You can fix it this way:
def main():
score1 = input("What is the first test score? ")
score2 = input("What is the second test score? ")
score3 = input("What is the third test score? ")
scoreaverage = score1 + score2 + score3
score = (scoreaverage / 3)
grade = 'Unknown'
if score < 60:
grade="F"
elif score < 70:
grade="C"
elif score < 80:
grade="B"
elif score < 90:
grade="A"
print "%s is the student's grade average!" % grade
main()
Welcome to SO. As explained by others, your problem was accessing grade before assigning a value to it. Here is another suggestion for doing what you want to do: (see the comments)
#disregard next line if you are using Python 3.3
from __future__ import division
#use a list to store the scores
scores = []
#if you are using 2.7 replace input with raw_input
#use float() to convert the input to float
scores.append(float(input("First score? ")))
scores.append(float(input("Second score? ")))
scores.append(float(input("Third score? ")))
#More general way of calculating the average
score = sum(scores) / len(scores)
#You could use a dictionary for score-grade mapping
grades = {100: 'A', 90: 'A', 80: 'B',
70: 'C', 60: 'D', 50: 'E',
40: 'F', 30: 'F', 20: 'F',
10: 'F', 0: 'F'}
#removes the remainder from the score
#to make use of the above dictionary
grade = grades[score - (score % 10)]
#Use string formatting when printing
print('grade: %s, score: %.2f' % (grade, score))
Your grade comparisons are off by 10 points. You won't assign anything to grade if score is between 90 and 100. And a piece of advice for a newbie programmer: Use a debugger. You'd have discovered the problem in just a few minutes had you stepped through it.
Try:
if score < 60:
grade="F"
elif score < 70:
grade="D"
elif score < 80:
grade="C"
elif score < 90:
grade="B"
else:
grade="A"

Categories