variables not defined in if statements for change counting program - python

I'm making a change counter and I'm having trouble printing the percentage for a grade, whenever I run the program I can enter as many inputs as I want, however, when I type done, which is supposed to terminate the program and leave the user with the percentage and letter grade, it just ends the program. If I could get any advice it would be greatly appreciated.
here's my code:
grade=""
total=0
count=1
scores=''
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
percentage=(numeric*10/count)
elif percentage >= 92 and percentage < 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
elif percentage >= 80 and percentage < 87:
letter = 'B'
elif percentage >=77 and percentage < 80:
letter = 'C+'
elif percentage >=70 and percentage < 77:
letter = 'C'
elif percentage >= 67 and percentage < 70:
letter = 'D+'
elif percentage >= 60 and percentage < 67:
letter = 'D'
elif percentage < 60 and percentage >= 0:
letter= 'F'
elif (numeric) < 0:
print("Score must be between 0 and 10")
elif (numeric) > 10:
print("Score must be between 0 and 10")
elif (scores)== 'done':
print(percentage,"% and you got an, ",letter)

Your conditional logic is flawed. You are never assessing the grade (letter) if the score.isdigit():
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
percentage=(numeric*10/count)
if percentage >= 92 and percentage < 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
...
It is often cleaner to jump out of the loop if the initial condition is false, e.g.:
while scores != 'done':
scores=input("Enter Homework score: ")
if not scores.isdigit():
continue
numeric=int(scores)
percentage=(numeric*10/count)
if 92 <= percentage < 100:
letter = 'A'
elif 87 <= percentage < 92:
letter = 'B+'
...
Also in python your shouldn't be afraid of exceptions. A common idiom in python is EAFP (Easier to Ask for Forgiveness than Permission):
while scores != 'done':
scores=input("Enter Homework score: ")
try:
numeric = int(scores)
except ValueError:
continue
You might also want to think about better ways of doing the large grade if elif elif ... block. E.g. an alternative approach would be define a dictionary of the grades:
grades = {'A': (92, 100), 'B+': (87, 92)} # Etc..
score = 93
_, letter = max((low <= score < high, letter) for letter, (low, high) in grades.items())
print(letter) # 'A'

Your code should look similar to the one below. Although I still cannot assess the logic behind your program (because you did not explain that in your question, e.g. percentage=(numeric*10/count) does not seem quite right to me, etc.), but the code below solves your current problem (based on your current question).
grade=""
total=0
count=1
scores=''
percentage = 0
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
if numeric < 0:
print("Score must be between 0 and 10")
elif numeric > 10:
print("Score must be between 0 and 10")
percentage=(numeric*10/count)
if percentage >= 92 and percentage < 100: # I would change this to if percentage >= 92 and percentage <= 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
elif percentage >= 80 and percentage < 87:
letter = 'B'
elif percentage >=77 and percentage < 80:
letter = 'C+'
elif percentage >=70 and percentage < 77:
letter = 'C'
elif percentage >= 67 and percentage < 70:
letter = 'D+'
elif percentage >= 60 and percentage < 67:
letter = 'D'
elif percentage < 60 and percentage >= 0: #I would change this to else:
letter= 'F'
print(percentage,"% and you got an, ",letter)

Related

Grade calculator range and ValueError - Python

I'm new to python and have been trying to create a simple grade calculator which tells the user what grade they've achieved based on their final score they've inputted.
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except score not in range (0,101) or ValueError:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
However when I try to run the program, it disregards the range and value error and gives it a grade anyway. Is there any way to rectify this, and if possible how could I make the program more efficient. As I said, I'm new to python, so any feedback would be useful.
Just for fun, let's make it a Match Case statement:
Since you only accept integers, we can take and assign score to input with :=, then check if it's valid with str.isnumeric. If that's true then we'll make score an integer := and check if it's between 0 and 100.
We'll change the input statement if they don't put valid input the first time around.
def grades():
text = "Please enter your score between 0 and 100: "
while True:
if ((score := input(text)).isnumeric() and
(score := int(score)) in range(0, 101)):
break
else:
text = "Incorrect value. Please enter your score between 0 and 100: "
match score:
case x if x >= 90 : grade = 'A'
case x if x >= 80 : grade = 'B'
case x if x >= 70 : grade = 'C'
case x if x >= 60 : grade = 'D'
case x if x >= 50 : grade = 'E'
case _ : grade = 'F'
print(f'Grade: {grade}')
Please note that this will only work in Python 3.10 or greater.
Just do this:
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score > 100:
while True:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
if score <= 100:
pass
else:
break
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except:
print("Oops. sommthing went wrong")
grades();
I made some corrections to your code. I added some comments to help explain what is going on. Let me know if this solution works for you:
def grades():
while True:
# Start a loop to ask for user input:
score = int(input("Please enter your score between 0 and 100:"))
# If not in range 1, 100, print error message
if score in range(0, 101):
break
print('Incorrect value. Please enter your score between 0 and 100:')
# calculate grade:
if score >= 90:
print("Grade:A")
elif score >= 80:
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
if __name__ == '__main__':
grades()
Simply assert that the input is in the determined range before checking through score ranges. Really, there is no need for a try/except statement.
def grades():
while True:
score = int(input(...))
if 0 <= score <= 100:
break
# Invalid score
# Check score ranges
...
I have made changes to your code, please test to ensure it performs to expectations.
I have added a while True loop, which attempts to validate the score to be between 0 - 100. If a non-integer value is entered it will hit the ValueError exception. This loop will only exit when a number within the range is entered.
The if statements use interval comparators X <= score < Y. You can read more about interval comparators here.
The if statement was also removed out of the try - except to make debugging easier. The idea is to have the least code possible in try - except so that when an exception triggers, it would be caused by the intended code.
Lastly, you don't want to ask for the user input inside the exception as the user might enter something which may cause another exception which will go uncaught.
def grades():
while True:
# Perform basic input validation.
try:
# Gets the user input.
score = int(input("Please enter your score between 0 and 100: "))
# Checks if the number entered is within 0 - 100. Note that range is non-inclusive for the stop. If it is within 0 - 100 break out of the while loop.
if 0 <= score <= 100:
break
# If a non-integer is entered an exception will be thrown.
except ValueError:
print("Input entered is not a valid number")
# Checking of scores using interval comparison
if score >= 90:
print("Grade:A")
elif 80 <= score < 90:
print("Grade:B")
elif 70 <= score < 80:
print("Grade:C")
elif 60 <= score < 70:
print("Grade:D")
elif 50 <= score < 60:
print("Grade:E")
else:
print("Grade:F")

Using “and” operator to compare two values

Very new to python and trying to figure out how to use the and operator to check if a number is between 50 and 100. Tried using and, && and || , but just getting invalid syntax python parser-16 error. If I take the and or alternative out of the code, then it partly works and dosn't give me a error message, though it dosn't check if the value is below 100, so presumly it must the and part that I'm doing wrong?
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif x > 50 and < 100:
print("That is above 50!")
else:
print("That number is too high!")
close!
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif x > 50 and x < 100:
print("That is above 50!")
else:
print("That number is too high!")
if x > 50 and x < 100 you have to reference it each time you check if its true
Alternative solution:
x = int(input("Enter a number between 0 and 100: "))# for a better look
if x < 50:
print("That is below 50!")
elif 100 >= x >= 50:# the numbers 50 and 100 shall be inclusive in one of the three params
print("That is between 50 and 100!")
else:
print("That number is too high!")
To simplify it more, you can write as below.
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif 50 < x < 100:
print("That is above 50!")
else:
print("That number is too high!")
If x<50:
print('Below 50')
elif x>50 and x<100:
print('Between 50 and 100');
else:
print('Above 100');
Try this

Python Grading Program

So I need to make a program that grades 10 students individually, then displays the average grade for all 10 students.
I think this is how the grading should look, but im not sure how to set up a count on the number of times its graded, or how to set up the average function. Help would be most welcome. I am a horrible coder.
score = int(input("Enter a score between 0 and 100: "))
if score >=89:
print("The grade is an A")
elif score>=79:
print("The grade is a B")
elif score>=69:
print("The grade is a C")
elif score>=59:
print("The grade is a D")
else:
print("The grade is a F")
You can try using a counter variable that goes from 0-9 and use a while loop to check and increment that counter value and after each loop calculates the average and keeps doing this till the last value has been entered
Counter = 0
average = 0
while (Counter <= 10):
score = int(input("Enter a score between 0 and 100: "))
if score >= 89:
print("The grade is an A")
elif score >= 79:
print("The grade is a B")
elif score >= 69:
print("The grade is a C")
elif score >= 59:
print("The grade is a D")
else:
print("The grade is a F")
Counter = Counter + 1
average = (score + average)
average = average/Counter
print("Average of all 10 students:",average)
So right now the code is configured specifically for just 10 loops but you can give the user the power to determine this by suggesting a value to end the loop and the while loop will check for this value and when the loop sees the value it exits the loop and gives a value
Also with each loop there is a counter value that keeps increasing and an average value that holds the sum of the values entered and when the loop exits and average is calculated by dividing the sum by the counters and this gives the results
This should do the trick.
total = 0
for i in range(10):
score = int(input("Enter a score between 0 and 100: "))
if score >= 89:
print("The grade is an A")
elif score >= 79:
print("The grade is a B")
elif score >= 69:
print("The grade is a C")
elif score >= 59:
print("The grade is a D")
else:
print("The grade is a F")
total += score
print("Average of all 10 students:", total/10)
In the for loop you get the score of each student and then add it to the total of all students. When the loop ends you divide it with the total number of students so 10.
total score / total number of students total / 10
You can define a function that finds the average score. Store all the scores in a list and then pass the list as an argument in the function
def avg(scores): #assuming scores is the name of the list
avg = sum(scores)/len(scores)
return "Average score is {}".format(avg)
Or
return f'Average score is {avg}' #for python3
Not sure I understand what you mean by number of times it is graded but I think you can include a while loop and a variable that increases by 1 every time it grades.

Why am I getting this message invalid syntax?

i write code if statement but there is a wrong in it .
this is the code
mark = float(input('enter your mark : '))
if mark < 50:
result = 'failed'
elif mark >= 50 and < 75:
result = 'accepted'
elif mark >= 75 and < 85:
result = 'good'
elif mark >= 85 and < 90:
result = 'very good'
else:
result = 'excellent'
print(result)
the message appear is invalid syntax in line 4 about < assignment
any help here guys?
The proper syntax is either elif mark >= 50 and mark < 75: or elif 50 <= mark < 75:
mark >= 50 and < 75 is not a valid expression, you must write mark >= 50 and mark < 75 instead. Alternatively, you can use a chained comparison: 50 <= mark < 75.
This would be your code that actually runs:
mark = float(input('enter your mark : '))
if mark < 50:
result = 'failed'
elif mark >= 50 and mark < 75:
result = 'accepted'
elif mark >= 75 and mark < 85:
result = 'good'
elif mark >= 85 and mark < 90:
result = 'very good'
else:
result = 'excellent'
print(result)
As others stated mark >= 50 and < 85 is not valid in Python.

Dropping the lowest test score

I'm writing a python program that drops the lowest of four test scores. The program first prompts the user to enter their first four test scores, then the program should drop the lowest test score and take the average of the remaining three test scores. The program should then print the final letter grade. This is what I have so far and I keep receiving an error when dropping the lowest score.
#Enter four test scores as percentages (%)
test1 = int(input("Enter grade 1: 90"))
test2 = int(input("Enter grade 2: 80"))
test3 = int(input("Enter grade 2: 70)")
test4 = int(input("Enter grade 2: 80)")
#Drop lowest test score
print("The average, with the lowest score dropped" )
total =(test1 + test2 + test3)
#Calculate average
def calc_average(total):
return total /3
#Grade scale
def determine_score(grade):
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >=70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
#Calculate final letter grade
print("The final grade is")
main()
I tried to write a program with the things that I understood from you.
Here is the explanation:
Taking four grades from user.
Dropping the lowest one.
Taking average.
Giving a letter grade according to the average.
Here is the code:
test1 = int(input("Enter grade 1: "))
test2 = int(input("Enter grade 2: "))
test3 = int(input("Enter grade 3: "))
test4 = int(input("Enter grade 4: "))
x = min(test1,test2,test3,test4)
total = float(test1 + test2 + test3 + test4 - x)
avg = total / 3
print("Your average is " + str(avg))
def determine_letter(grade):
letter =""
if grade >= 90:
letter = "A"
elif grade >= 80:
letter = "B"
elif grade >= 70:
letter = "C"
elif grade >= 60:
letter = "D"
else:
letter = "F"
print("The final letter grade is " + letter)
determine_letter(avg)

Categories