Getting the average on random grades - python

Does anyone know how to get the average of the random grades? She wants to generate just random grades and get the average but I had also done one where you input the grades on your end but I don't think that's what she was looking for.
import random
grade = random.randint(50,100)
grade2 = random.randint(50,100)
grade3 = random.randint(50,100)
grade4 = random.randint(50,100)
grade5 = random.randint(50,100)
if int(grade) >= 90 and int(grade) <= 100:
print ("Grade 1:", grade, "A")
elif int(grade) >= 80 and int(grade) <=90:
print("Grade 1:", grade, "B")
elif int(grade) >= 70 and int(grade) <= 80:
print("Grade 1:", grade, "C")
elif int(grade) > 60 and int(grade) <=70:
print("Grade 1:", grade,"D")
elif int(grade) <= 60:
print("Grade 1:", grade, "F")
if int(grade2) >= 90 and int(grade2) <= 100:
print ("Grade 2:", grade2, "A")
elif int(grade2) >= 80 and int(grade2) <=90:
print("Grade 2:", grade2, "B")
elif int(grade2) >= 70 and int(grade2) <= 80:
print("Grade 2:", grade2, "C")
elif int(grade2) > 60 and int(grade2) <=70:
print("Grade 2:", grade2,"D")
elif int(grade2) <= 60:
print("Grade 2:", grade2, "F")
if int(grade3) >= 90 and int(grade3) <= 100:
print ("Grade 3:", grade3, "A")
elif int(grade3) >= 80 and int(grade3) <=90:
print("Grade 3:", grade3, "B")
elif int(grade3) >= 70 and int(grade3) <= 80:
print("Grade 3:", grade3, "C")
elif int(grade3) > 60 and int(grade3) <=70:
print("Grade 3:", grade3,"D")
elif int(grade3) <= 60:
print("Grade 3:", grade3, "F")
if int(grade4) >= 90 and int(grade4) <= 100:
print ("Grade 4:", grade4, "A")
elif int(grade4) >= 80 and int(grade4) <=90:
print("Grade 4:", grade4, "B")
elif int(grade4) >= 70 and int(grade4) <= 80:
print("Grade 4:", grade, "C")
elif int(grade4) > 60 and int(grade4) <=70:
print("Grade 4:", grade4,"D")
elif int(grade4) <= 60:
print("Grade 4:", grade4, "F")
if int(grade5) >= 90 and int(grade5) <= 100:
print ("Grade 5:", grade5, "A")
elif int(grade5) >= 80 and int(grade5) <=90:
print("Grade 5:", grade5, "B")
elif int(grade5) >= 70 and int(grade5) <= 80:
print("Grade 5:", grade5, "C")
elif int(grade5) > 60 and int(grade5) <=70:
print("Grade 5:", grade5,"D")
elif int(grade5) <= 60:
print("Grade 5:", grade5, "F")

If you find yourself putting a number after variable names, that's a big sign that you might want to use a list (or, in general, an iterable) to store the elements:
grades = [51, 62, 87, 57]
There are several ways to generate a list of random grades numpy.random.rand is one, but an easier way for a beginner might be to just start off with a list like
grades = []
and then create a loop to append the grades. Python provides a sum function to sum up all of the values in your list, and a len function to compute the number of elements in the list. With these functions, you can compute the grades.
You can also use a list comprehension to generate the grades if you're familiar with them.
If you go ahead and create the grades list, your code can be adapted as follows:
for idx, grade in enumerate(grades, 1):
label = f"Grade {idx}"
if int(grade) >= 90 and int(grade) <= 100:
print (label, grade, "A")
elif int(grade) >= 80 and int(grade) <=90:
print(label, grade, "B")
elif int(grade) >= 70 and int(grade) <= 80:
print(label, grade, "C")
elif int(grade) > 60 and int(grade) <=70:
print(label, grade,"D")
elif int(grade) <= 60:
print(label, grade, "F")
Here enumerate(grades, 1) returns an index and an element from grades, starting at 1 because we specify the 1 here.

As Kraigolas pointed out, you can eliminate a lot of copied+pasted code by putting the grades into a list instead of 5 individual variables, and using enumerate to generate the "grade 1", "grade 2", etc.
The easiest way to get an average is to use statistics.mean, which gives you the mean (average) value of any list that you pass to it:
>>> grades = [70, 80, 85]
>>> import statistics
>>> statistics.mean(grades)
78.33333333333333
I'd also suggest putting the logic to determine a letter grade into a function, like this:
def letter_grade(grade: float) -> str:
assert 0 <= grade <= 100
for score, letter in [
(90, "A"),
(80, "B"),
(70, "C"),
(60, "D"),
]:
if grade >= score:
return letter
return "F"
Now you can put it all together with a very small amount of code:
import random
import statistics
grades = [random.randint(50, 100) for _ in range(5)]
for n, grade in enumerate(grades, 1):
print(f"Grade {n}: {letter_grade(grade)}")
print(f"Average: {letter_grade(statistics.mean(grades))}")
Sample output:
Grade 1: F
Grade 2: A
Grade 3: A
Grade 4: A
Grade 5: A
Average: B

Related

Python for everybody assignment 3.3

Why wouldn't my for loop work? If I put in 0.85 for grade score it'd print out F and error message instead of B. Why is this?
grade=input('Score Grade:')
fg=float(grade)
for fg in range(0,1):
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
print('error grade out of range')
quit()
You are misusing the range() function. range() is used to iterate over multiple values, not to validate if a number is in a range. You should instead check that fg greater than or equal to 0, or less than or equal to 1. Like this:
grade=input('Score Grade:')
fg=float(grade)
if 0 > fg or 1 < fg:
print('error grade out of range')
quit()
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
you are doing this for one time you dont need to use a loop
you can do this
grade = float(input('Score Grade:'))
if grade < 1 and grade > 0:
if grade > 0.9:
print('A')
elif grade >= 0.8:
print('B')
elif grade >= 0.7:
print('C')
elif grade >= 0.6:
print('D')
elif grade < 0.6:
print('F')
else:
print('error grade out of range')
quit()
You do not need to use for operator neither range. The simplest solution is:
'''
grade = input("Enter number:")
try:
grade = float(grade)
except:
grade = -1
if grade >= 0.9:
print("A")
elif grade >= 0.8:
print("B")
elif grade >= 0.7:
print("C")
elif grade >= 0.6:
print("D")
elif grade < 0.6:
print("F")
else:
print("Error!")
quit()
'''

Make a key selection and loop function until another key i pressed

I am trying to set up this code to run three functions c1, c2 and c3 on a keypress and once the selection is made I would like the code to loop indefinitely and keep asking for input value until a new key is pressed.
Now the code waits for keyboard.read_key() every time and doesn't quite do what I want to do, I understand I have to change the while to make it loop on the function rather than the keypress but I also want to stop the function when a different key is pressed.
I am a bit lost.
If anyone could point me in the right direction would be greatly appreciated!
import keyboard
grade1 = 10
grade2 = 20
grade3 = 30
grade4 = 40
grade5 = 50
grade6 = 60
grade7 = 70
grade8 = 80
grade9 = 90
def c1():
print('c1')
grade = float(input('Select grade: '))
if grade < grade1:
print('Grade 0')
elif grade >= grade1 and grade <= grade2:
print('Grade 1')
elif grade > grade2 and grade <= grade3:
print('Grade 1')
elif grade > grade3 and grade <= grade4:
print('Grade 3')
elif grade > grade4 and grade <= grade5:
print('Grade 4')
elif grade > grade5 and grade <= grade6:
print('Grade 5')
elif grade > grade6 and grade <= grade7:
print('Grade 6')
elif grade > grade7 and grade <= grade8:
print('Grade 7')
elif grade > grade8 and grade <= grade9:
print('Grade 8')
elif grade > grade9:
print('Grade 9')
def c2():
print('c2')
grade = float(input('Select grade: '))
if grade < grade1:
print('Grade 0')
elif grade >= grade1 and grade <= grade2:
print('Grade 1')
elif grade > grade2 and grade <= grade3:
print('Grade 1')
elif grade > grade3 and grade <= grade4:
print('Grade 3')
elif grade > grade4 and grade <= grade5:
print('Grade 4')
elif grade > grade5 and grade <= grade6:
print('Grade 5')
elif grade > grade6 and grade <= grade7:
print('Grade 6')
elif grade > grade7 and grade <= grade8:
print('Grade 7')
elif grade > grade8 and grade <= grade9:
print('Grade 8')
elif grade > grade9:
print('Grade 9')
def c3():
print('c3')
grade = float(input('Select grade: '))
if grade < grade1:
print('Grade 0')
elif grade >= grade1 and grade <= grade2:
print('Grade 1')
elif grade > grade2 and grade <= grade3:
print('Grade 1')
elif grade > grade3 and grade <= grade4:
print('Grade 3')
elif grade > grade4 and grade <= grade5:
print('Grade 4')
elif grade > grade5 and grade <= grade6:
print('Grade 5')
elif grade > grade6 and grade <= grade7:
print('Grade 6')
elif grade > grade7 and grade <= grade8:
print('Grade 7')
elif grade > grade8 and grade <= grade9:
print('Grade 8')
elif grade > grade9:
print('Grade 9')
def wait():
keyboard.read_key()
def close():
quit()
keyboard.add_hotkey('a', c1)
keyboard.add_hotkey('b', c2)
keyboard.add_hotkey('c', c3)
keyboard.add_hotkey('q', close)
while True:
wait()

How may I get the desired output in my code?

I was attempting to solve some python excercise. I came across a question and that has made me feel bored. Please will you resolve it?
A school has following rules for grading system:
Below 25 - F
25 to 45 - E
45 to 50 - D
50 to 60 - C
60 to 80 - B
Above 80 - A
Ask user to enter marks and print the corresponding grade.
print("My mark is ")
a = input()
if '25 > a':
print('F')
elif a < 25 and a > 45:
print('E')
elif 45 <= a and a >|= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
My expected result was different grades for different numbers but instead got only F for every input I do...
print("My mark is ")
a = int(input())
if a < 25:
print('F')
elif a >= 25 and a < 45:
print('E')
elif a >= 45 and a < 50:
print('D')
elif a >= 50 and a < 60:
print('C')
elif a >= 60 and a < 80:
print('B')
else:
print('A')
first of all, you should cast input to int. then, you just compare it and "a" should be the first in comparing like a > 25, not 25 < a
Multiple issues..
Remove the outside quotes of your if statements as those are strings.
elif '45 <= a and a => 50': the order must be >=
And you must compare with an int so you need to do int(input()) or another variation of converting to int type.
a = int(input('What is the grade?'))
print("My mark is ")
if 25 > a:
print('F')
elif a <= 25 and a > 45:
print('E')
elif 45 <= a and a >= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
your code needs a little clean up. Dont use quotation around the condition which is supposed to be Boolean
a = input("My mark is ")
a=int(a)
if (25 > a):
print('F')
elif a <= 25 and a > 45:
print('E')
elif 45 <= a and a >= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')

python programming- average of exams and assignments and print grade

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

determining average grades and displaying letter grades

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. :)

Categories

Resources