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()
'''
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
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?
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
Im expecting the input for "score" to be a number only. To do that would I simply use "score = int"
def get_letter_grade(score):<br/>
score = int
if score >= 90:
return "A"
elif score >= 80:
return "B"
You can try this:-
def get_letter_grade(score):
if isinstance(score,int):
if score >= 90:
return "A"
elif score >= 80:
return "B"
def get_letter_grade(score):
try:
val = int(score)
if val>= 90:
return "A"
elif val >= 80:
return "B"
except ValueError:
return("That's not an int!")
print(get_letter_grade(92))
print(get_letter_grade("test"))
Output:
A
That's not an int!
temp = 120
if temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
Python picks the first condition that is true, and the rest of the if..elif..else branches are skipped.
120 > 85 is true, so the first test passes and 'Hot' is printed. It doesn't matter that the second test also matches after that point.
Put the > 100 test first:
if temp > 100:
print "REALLY HOT!"
elif temp > 85:
print "Hot"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
Alternatively, limit the tests to exclude the upper range:
if 100 >= temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"