I am a beginner with python and I am working with this project that will print the result of the students.I am done with nearly everything execpt the percentage.See,in my code,the program will only print the percentage of the last person's marks.I need to make it so that it calculates percentage for everyone individually and then print it at the end.Your help will be much appreciated.Thanks
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
percentage =(marks / T_marks) * 100
elif ask == "print":
for (key,value) in data.items():
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
You need to compute percentage under the print case, this should get you what you want:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
elif ask == "print":
for (key,value) in data.items():
# NOTE percentage is under the case when user asks for print
percentage =(value / T_marks) * 100
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
Also two hints: This code will output "You failed" if someone got a grade of 90. You need to set equality at 90 for one of the cases. Also python has simplified comparisons where and is not needed. Here is a simplified version, and corrected for case of 90 to get an A grade:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
elif ask == "print":
for (key,value) in data.items():
percentage =(value / T_marks) * 100
print(key,"::",value)
if percentage >= 90:
print("Passed with A grade")
elif 90 > percentage >= 70:
print("Passed with B grade")
elif 70 > percentage >= 60:
print("Passed with C grade")
elif 60 > percentage >= 50:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
The input() method reads a string, but you cannot convert e. g. "4 4 4 5" to int. Method split() without arguments creates a list of the words in string as follow:
"4 5 5" -> ["4", "5", "5"]
Change your input to:
marks_string = input("Enter marks: ")
marks = [int(mark) for mark in marks_string.split()] # convertion to int
And change calculate of percentage:
percentage =(sum(marks) / T_marks) * 100
Indentation, fixed in edit:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
percentage =(marks / T_marks) * 100
elif ask == "print":
for (key,value) in data.items():
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
>>> What do you want? y
>>>Enter your name: Alex
>>>Enter marks: 12
>>>What do you want? y
>>>Enter your name: Michael
>>>Enter marks: 22
>>>What do you want? print
>>>Alex :: 12
>>>You failed
>>>Michael :: 22
>>>You failed
>>>What do you want?
Related
im working on a python grade calculator for class where i can only use if/else/elif statements to drop the lowest score and then average the scores. this is what i have so far but i dont know how to determine the lowest score from the input using ONLY if/else statements. any help is appreciated!
# Input
sName = str(input("Name of person that we are calculating the grades for: "))
iTest1 = int(input("Test 1: "))
iTest2 = int(input("Test 2: "))
iTest3 = int(input("Test 3: "))
iTest4 = int(input("Test 4: "))
sDrop = str(input("Do you wish to drop the lowest grade Y or N? "))
# Test If Statements
if iTest1 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
if iTest2 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
if iTest3 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
if iTest4 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
# Drop Lowest If Statements
if sDrop != "Y" or "N" or "y" or "n":
print("Enter Y or N to drop the lowest grade.")
raise SystemExit
# Grade Scale
if score >= 97.0:
grade = "A+"
elif score >= 94.0 and score <= 96.9:
grade = "A"
elif score >= 90.0 and score <= 93.9:
grade = "A-"
elif score >= 87.0 and score <= 89.9:
grade = "B+"
elif score >= 84.0 and score <= 86.9:
grade = "B"
elif score >= 80.0 and score <= 83.9:
grade = "B-"
elif score >= 77.0 and score <= 79.9:
grade = "C+"
elif score >= 74.0 and score <= 76.9:
grade = "C"
elif score >= 70.0 and score <= 73.9:
grade = "C-"
elif score >= 67.0 and score <= 69.9:
grade = "D+"
elif score >= 64.0 and score <= 66.9:
grade = "D"
elif score >= 60.0 and score <= 63.9:
grade = "D-"
else:
grade = "F"
Test the first two to find the smallest of those. Now compare the other two in turn to smallest and update smallest if necessary.
if iTest1 < iTest2:
smallest = iTest1
else:
smallest = iTest2
if iTest3 < smallest:
smallest = iTest3
if iTest4 < smallest:
smallest = iTest4
Of course, all of this is a tedious way to write:
smallest = min([iTest1, iTest2, iTest3, iTest4])
print('Hello, welcome to your grade calculator.')
GradeCount = 0
totalGrades = 0.0
moreStudent = 'y'
while moreStudent == 'y' or moreStudent == 'Y':
grade = float(input('Enter a grade or a -1 to end: '))
while grade != -1:
if grade > 100 or grade < 0:
print('Invalid input. Please enter a value between 1 and 100.')
grade = float(input('Enter the next grade or -1 to end: '))
continue
totalGrades = totalGrades + grade
GradeCount = GradeCount + 1
if 90 <= grade <=100:
print('You got an A. Thats awesome.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif 80 <= grade < 90:
print('You got a B. Good job.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif 70 <= grade < 80:
print('You got a C. Thats fine I guess.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif 60 <= grade < 70:
print ('You got a D. Not very good.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif grade < 60:
print ('You got an F. You fail.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
grade = float(input('Enter the next grade or -1 to end: '))
moreStudent = input('Are you a new student and ready to enter your
grades? y or n: ')
print ('Number of grades entered:', GradeCount)
print ('Class total:',totalGrades)
print ('Class grade average:', format(totalGrades / GradeCount, '.2f'))
How can I make it so the user only has 2 tries before the program issues an error message then clears the screen and starts over? Also how can I make it clear the screen every time there is a new user?
The most basic modification you could use to the current code is to add a counter, other methods can be used as well
while moreStudent == 'y' or moreStudent == 'Y':
grade = float(input('Enter a grade or a -1 to end: '))
count = 0
while grade != -1:
if grade > 100 or grade < 0:
count += 1
if count == 2:
moreStudnet = 'n'
break
else:
print('Invalid input. Please enter a value between 1 and 100.')
grade = float(input('Enter the next grade or -1 to end: '))
continue
totalGrades = totalGrades + grade
GradeCount = GradeCount + 1
I’m trying to make a system where, if you input a number, it tells you what grade it would be, but it doesn’t work.
My code is
percentage = input(“Please input a number”)
if percentage == 100:
Grade = (“A*”)
print (“A”)
elif percentage ==80:
Grade = (“A”)
print (“A”)
elif percentage == 60:
Grade = (“B”)
print (“B”)
elif percentage == 40:
Grade = (“C”)
print (“C”)
else:
Grade == (“D”)
print (“D”)
The error says
NameError: name ‘grade’ is not defined
Help, sorry in advance if I missed something obvious
The below code working in python2.7.
percentage = input("Please input a number")
if percentage == 100:
Grade = ("A*")
print ("A*")
elif percentage ==80:
Grade = ("A")
print ("A")
elif percentage == 60:
Grade = ("B")
print ("B")
elif percentage == 40:
Grade = ("C")
print ("C")
else:
Grade = ("D")
print ("D")
== and = are different operations. == is comparison while = is assignment.
Try the following code:
percentage = int(input("Please input a number"))
if percentage == 100:
grade = "A*"
elif percentage == 80:
grade = "A"
elif percentage == 60:
grade = "B"
elif percentage == 40:
grade = "C"
else:
grade = "D"
print(grade)
Please learn about Comparisons
I think this is what you are trying to achieve:
percentage = int(input("Please input a number: "))
grade = ''
if percentage == 100:
grade = "A*"
elif percentage == 80:
grade = "A"
elif percentage == 60:
grade = "B"
elif percentage == 40:
grade = "C"
else:
grade = "D"
print(grade)
There are a number of things going on here.
Your input is a string, but you're comparing it to an int (always false).
You are only checking exact percentages, what about ranges? In your code, an input percent of 81 would result in a D grade, probably not the result you want for real-world input data.
Try something like this:
from collections import OrderedDict as od
CUTOFFS = od()
CUTOFFS[100.0] = 'A*'
CUTOFFS[80.0] = 'A'
CUTOFFS[60.0] = 'B'
CUTOFFS[40.0] = 'C'
CUTOFFS[0.0] = 'D'
def percent_to_grade(p):
for k, v in CUTOFFS.items():
if k <= float(p):
return v
raise ValueError('Invalid CUTOFFS data')
def get_grade(percent=None):
while True:
if percent is not None:
try:
percent = float(percent)
if percent < 0.0 or percent > 100.0:
percent = None
raise ValueError('Invalid value for percent')
break
except Exception as exc:
print str(exc), 'Trying again ...'
percent = input('What is your grade? ')
##
grade = percent_to_grade(percent)
return grade
def test():
vals = [100, 80, 79.9, 39, 0, -2, 'TBD', None]
for v in vals:
print v, get_grade(v)
print
Run the test function to see this in action:
>>> test()
100 A*
80 A
79.9 B
39 D
0 D
-2 Invalid value for percent Trying again ...
What is your grade? 10
D
TBD could not convert string to float: TBD Trying again ...
What is your grade? 20
D
None What is your grade? 30
D
I gave manual input to the last three so we could see all test cases.
Please im trying to Write a Python program that calculates a student Final grade for a class that has two assignments and two exams. Assignments worth 40% of the class grade and exams worth 60% of the class grade. The program should perform the following steps:
Ask the user for assignment1, assignment2, exam1, and exam2 grades. all grades are out of 100 .
Calculate the average of the assignments.
Calculate the average of the exams.
Calculate the final grade using the following formula:
final grade=.4*average of the assignments+.6*average of the exams.
Format the final grade to have 2 decimal places.
Display a message telling the student what the final grade is.
here is my program:
from math import *
def main():
Assignment1 = eval(input("Please enter the score for Assignment 1: "))
Assignment2 = eval(input("Please enter the score for Assignment 2: "))
Assignment_total = Assignment1 + Assignment2
Assignment_average = Assignment_total/2
print("The average of the assignment is", round(Assignment_average, 2))
Exam1 = eval(input("Please enter the score for Exam 1: "))
Exam2 = eval(input("Please enter the score for Exam 2: "))
Exam_total = Exam1 + Exam2
Exam_average = Exam_total/2
print("The average of the Exam is", round(Exam_average, 2))
Final_grade = 0.4 * Assignment_average + 0.6 * Exam_average
if 90 <= Final_grade <= 100:
return 'A'
elif 80 <= Final_grade <= 89:
return 'B'
elif 70 <= Final_grade <= 79:
return 'C'
elif 60 <= Final_grade <= 69:
return 'D'
else:
return 'F'
main()
i cannot get it to print The grades. please help me
You are all over the page here. You have return but you are not returning anything (i.e. you would have to call grade = main() and then print(grade).
Take a look at my comments below:
# nothing you are doing requires the math module
# eval() and round() are built-ins; we dont even need eval()
## from math import *
def main():
# variable names = short & sweet + meaningful
a1 = int(input("Please enter the score for Assignment 1: "))
a2 = int(input("Please enter the score for Assignment 2: "))
atot = a1 + a2
aavg = atot / 2
print ("The average of the assignment is", round(aavg, 2))
e1 = int(input("Please enter the score for Exam 1: "))
e2 = int(input("Please enter the score for Exam 2: "))
etot = e1 + e2
eavg = etot / 2
print ("The average of the Exam is", round(eavg, 2))
fingrd = ((0.4 * aavg) + (0.6 * eavg))
if (90 <= fingrd <= 100):
print (fingrd, ': A') # edit: included print format you commented
# no need to do <= on the upper bounds
# < upper_bound includes <= your previous lower_bound - 1
# i.e. 80 <= fingrd < 90 equates to 80 <= fingrd < 90
elif (80 <= fingrd < 90):
print (fingrd, ': B')
elif (70 <= fingrd < 80):
print (fingrd, ': C')
elif (60 <= fingrd < 70):
print (fingrd, ': D')
else:
print (fingrd, ': F')
if __name__ == '__main__':
main()
Output:
Please enter the score for Assignment 1: 70
Please enter the score for Assignment 2: 100
The average of the assignment is 85.0
Please enter the score for Exam 1: 45
Please enter the score for Exam 2: 87
The average of the Exam is 66.0
73.6 : C
Taking my suggestion and #Toad22222's and also getting rid of that scary eval:
from math import *
def main():
Assignment1 = int(input("Please enter the score for Assignment 1: "))
Assignment2 = int(input("Please enter the score for Assignment 2: "))
Assignment_total = Assignment1 + Assignment2
Assignment_average = Assignment_total/2
print("The average of the assignment is", round(Assignment_average, 2))
Exam1 = int(input("Please enter the score for Exam 1: "))
Exam2 = int(input("Please enter the score for Exam 2: "))
Exam_total = Exam1 + Exam2
Exam_average = Exam_total/2
print("The average of the Exam is", round(Exam_average, 2))
Final_grade = 0.4 * Assignment_average + 0.6 * Exam_average
print("The final grade is", round(Final_grade, 2))
if 90 <= Final_grade <= 100:
print('A')
elif 80 <= Final_grade <= 89:
print('B')
elif 70 <= Final_grade <= 79:
print('C')
elif 60 <= Final_grade <= 69:
print('D')
else:
print('F')
main()
UPDATE
Kind of a rewrite just for fun. Feel free to ignore or take inspiration or ask questions.
import collections
Component = collections.namedtuple("Component", ["name", "count", "weight"])
def get_average(name, how_many):
return sum(
int(input("Please enter the score for {} {}: ".format(name, i+1)))
for i in range(how_many)
) / how_many
def main():
components = [
Component(name="assignment", count=2, weight=0.4),
Component(name="exam", count=2, weight=0.6),
]
total = 0
for component in components:
average = get_average(component.name, component.count)
print("The average of the {}s is: {:.2f}".format(component.name, average))
print()
total += average * component.weight
letters = [(90, "A"), (80, "B"), (70, "C"), (60, "D")]
grade = next((letter for score, letter in letters if total >= score), "F")
print("The final grade is: {:.2f} ({})".format(total, grade))
main()
You need to call the function by assigning it to a variable to then print. See below:
from math import *
def main():
Assignment1 = eval(input("Please enter the score for Assignment 1: "))
Assignment2 = eval(input("Please enter the score for Assignment 2: "))
Assignment_total = Assignment1 + Assignment2
Assignment_average = Assignment_total/2
print("The average of the assignment is", round(Assignment_average, 2))
Exam1 = eval(input("Please enter the score for Exam 1: "))
Exam2 = eval(input("Please enter the score for Exam 2: "))
Exam_total = Exam1 + Exam2
Exam_average = Exam_total/2
print("The average of the Exam is", round(Exam_average, 2))
Final_grade = round(0.4 * Assignment_average + 0.6 * Exam_average)
if 90 <= Final_grade <= 100:
return "Your final grade is %s: A" %(Final_grade)
elif 80 <= Final_grade <= 89:
return "Your final grade is %s: B" %(Final_grade)
elif 70 <= Final_grade <= 79:
return "Your final grade is %s: C" %(Final_grade)
elif 60 <= Final_grade <= 69:
return "Your final grade is %s: D" %(Final_grade)
else:
return "Your final grade is %s: F" %(Final_grade)
mygrades = main()
print (mygrades)
Output
Please enter the score for Assignment 1: 43
Please enter the score for Assignment 2: 88
The average of the assignment is 65.5
Please enter the score for Exam 1: 90
Please enter the score for Exam 2: 89
The average of the Exam is 89.5
Your final grade is 80: B
I'm working on a program for class that finds the average of 5 entered test scores then displays the letter grades relevant to each letter score. letter score is a 10 point system ( A = 90-100 B = 80-89, etc)
This is what I've put together so far but it doesn't seem to recognize "avg" in the syntax. any suggestions?
def main():
while true:
grade = int(input('Enter grade: '))
total += grade
avg = calc_average(total)
abc_grade = determine_grade(grade)
print('Average grade is: ' avg)
print('Letter grades for entered grades are: ' abc_grade)
def calc_average(total):
return total / 5
def determine_grade(grade):
if grade >= 90 and <= 100:
return 'A'
elif grade >= 80 and <= 89:
return 'B'
elif grade >= 70 and <= 79:
return 'C'
elif grade >= 60 and <= 69:
return 'D'
else:
return 'F'
main()
use:
print('Average grade is: '+str(avg))
print('Letter grades for entered grades are: '+abc_grade)
or
print('Average grade is: %.2f'%(avg))
print('Letter grades for entered grades are: %s'%(abc_grade))
_list = []
def calc_average(total):
return total / 5
def determine_grade(grade):
if grade >= 90 and grade <= 100:
return 'A'
elif grade >= 80 and grade <= 89:
return 'B'
elif grade >= 70 and grade <= 79:
return 'C'
elif grade >= 60 and grade <= 69:
return 'D'
else:
return 'F'
while True:
grade = int(input('Enter grade: '))
_list.append(grade)
avg = calc_average(sum(_list))
abc_grade = ' '.join([determine_grade(mark) for mark in _list])
if len(_list) > 5:
break
print('Average grade is: ', avg)
print('Letter grades for entered grades are: ', abc_grade)
def main():
print("This is a program which displays the grade from a score")
print("")
grade = eval(input("What is the value of the score : "))
print("")
if 90 <= grade <= 100:
print("Your get an A")
elif 80 <= grade <= 89:
print("Your get a B")
elif 70 <= grade <= 79:
print("Your get a C")
elif 60 <= grade <= 69:
print("Your get a D")
else:
print("Your get an F")
main()
This Worked for me.. A few minor changes except your code is working fine.
def main():
total = 0;avg = 0;abc_grade = 0
def calc_average(total):
return total / 5
def determine_grade(grade):
if 90 <= grade <= 100:
return 'A'
elif 80 <= grade <= 89:
return 'B'
elif 70 <= grade <= 79:
return 'C'
elif 60 <= grade <= 69:
return 'D'
else:
return 'F'
while(True):
grade = int(input('Enter grade: '))
total += grade
avg = calc_average(total)
abc_grade = determine_grade(grade)
print('Average grade is: ' + str(avg))
print('Letter grades for entered grades are: ' + str(abc_grade))
main()
Hope you can find out differences. :)