not printing count or average regardless of indentation - python-3.x

I have to make a program that allows the user to enter grades until they enter a negative, and then output the number of passing grades and failing grades with the average. we aren't allowed to use the list function.
maxgrade = 100
mingrade = 0
passing = 0
failing = 0
while True:
try:
grade = int(input("Enter a grade: "))
if 100 >= grade > 60:
passing += 1
elif grade <= 60:
failing += 1
if grade < 0:
print("Invalid")
if grade < mingrade:
mingrade = grade
if grade > maxgrade:
maxgrade = grade
total == grade
count = passing + failing
avg = total/count
print("Average: ", avg)
print("# Passing: ", passing)
print("# Failing: ", failing)
except:
print("Invalid")
break

First, as I mentioned in the comment, your usage of try and except is incorrect. Try and except are used in tandem to prevent errors from occurring. In your case however, I doubt that try and except is even needed. See below code for the workaround.
You also need to take into account your logic and code execution order. The following annotated code will work as specified.
# Assume the lowest and highest possible for max and min grades, respectively
max_grade = 0
min_grade = 100
grade_sum = 0
passing_count = 0
failing_count = 0
# Loop sentinel
running = 1
# Main loop
while running:
# Input validation sentinel
invalid_input = 1
# Input validation loop
while invalid_input:
grade = input("Enter a grade: ")
if grade.isnumeric():
grade = int(grade)
invalid_input = 0
else:
print("Please enter a number!")
# Increment number of passing or failing grades
if 100 >= grade > 60:
passing_count += 1
elif 60 >= grade >= 0:
failing_count += 1
else:
running = 0
# Update grade_sum
grade_sum += grade
# Update min_grade and max_grade
if grade < min_grade:
min_grade = grade
if grade > max_grade:
max_grade = grade
# Calculate grade average
grade_avg = grade_sum / (passing_count + failing_count)
# Print results
print("Average: ", grade_avg)
print("# Passing: ", passing_count)
print("# Failing: ", failing_count)

Related

Find average of given numbers in input

I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")

how can make the Lists that i have appended within the lists appear on different lines when printed altogethor in python?

I want to create a report card like program as a part of a school coding project, it has to be simple and use some basic functions and loops in python.
`sn = int(input("Enter Number of Students: "))
reportCard = []
header = ["Name","Total","Average","Result","Grade"]
for i in range(sn):
reportCard.append([])
name = str(input("Name of Student: "))
m1 = float(input("enter achieved marks in First Subject: "))
m2 = float(input("enter achieved marks in Second Subject: "))
m3 = float(input("enter achieved marks in Third Subject: "))
total = m1 + m2 + m3
average = total/3
ResultS = " "
grade = " "
if average >= 60:
ResultS = "Passed"
else:
ResultS= "Failed"
if average < 60:
grade = "F"
elif average <= 70:
grade = "D"
elif average <= 75:
grade = "C"
elif average <= 80:
grade = "B"
elif average <= 85:
grade = "A-"
elif average <= 90:
grade = "A"
elif average <= 95:
grade = "A+"
elif average <= 100:
grade = "A*"
x = [name, total, average, ResultS, grade]
reportCard[i].append(x)
if i == sn-1:
print()
print ("Report Card")
print()
print("Name","Total","Average","Result","Grade")
print(*reportCard)
break`
The output needs to look like this:
Name total average results Grade
name total average results grade
but looks like this instead=
Name total average results Grade, name total average results grade
any ideas how to get it fixed??
You need to use \n to change to a new line.
print("Name","Total","Average","Result","Grade\n")
print(*reportCard)
Some other escape characters:
https://python-reference.readthedocs.io/en/latest/docs/str/escapes.html

How do I sort out this "NameError"?

def Get_Details():
Student_Name = input("Enter the name of the student: ")
Coursework_Mark = int(input("Enter the coursework mark achieved by the student: "))
while Coursework_Mark < 0 or Coursework_Mark >60:
print("Try again, remember the coursework mark is out of 60.")
Coursework_Mark = int(input("Enter the coursework mark achieved by the student: "))
Prelim_Mark = int(input("Enter the prelim mark achieved by the student: "))
while Prelim_Mark < 0 or Prelim_Mark > 90:
print("Try again, remember the prelim mark is out of 90.")
Prelim_Mark = int(input("Enter the prelim mark achieved by the student: "))
return Student_Name, Coursework_Mark, Prelim_Mark
def Calculate_Percentage(Coursework_Mark, Prelim_Mark):
Percentage = ((Coursework_Mark + Prelim_Mark)/150) * 100
if Percentage >= 70:
Grade = "A"
elif 60 >= Percentage <= 69:
Grade = "B"
elif 50 >= Percentage <= 59:
Grade = "C"
elif 45 >= Percentage <= 50:
Grade = "D"
else:
Grade = "No Award"
return Percentage, Grade
def Display_Results(Student_Name, Grade):
print(Student_Name + " achieved a grade " + str(Grade) + ".")
#MAIN PROGRAM
Student_Name, Coursework_Mark, Prelim_Mark = Get_Details()
Percentage = Calculate_Percentage(Coursework_Mark, Prelim_Mark)
Display_Results(Student_Name, Grade)
At the end of the program I receieve:
Program.py", line 41, in <module>
Display_Results(Student_Name, Grade)
NameError: name 'Grade' is not defined
How can this be fixed? Please help, thank you.
This program asks the user their name, coursework mark (out of 60) and prelim mark (out of 90) and calculates their percentage which is send to their screen as a grade along with their name.
Function Calculate_Percentage returns two values, Percentage and Grade. It looks like you wanted to assign them to a separate variable each exactly like you did with three values from the Get_Details call in the line above.
So last two lines should look like this:
Percentage, Grade = Calculate_Percentage(Coursework_Mark, Prelim_Mark)
Display_Results(Student_Name, Grade)
Please use a Pythonic naming convention to make your code more readable. For example variable names are usually all_lower_case.

Cannot keep certain numbers from averaging

I need help. I'm trying to run the program below. When I enter a number above 100 or below 0 I need it to disregard that input any advice?
total = 0.0
count = 0
data = int(input("Enter a number or 999 to quit: "))
while data != "":
count += 1
number = float(data)
total += number
data = int(input("Enter a number or 999 to quit: "))
try:
data = int(data)
except ValueError:
pass
average = round(total) / count
if data == 999:
break
elif data >= 100:
print("error in value")
elif data <= 0:
number = 0
print("error in value")
print("These", count, "scores average as: ", round(average, 1))
You could move the average = ... line behind the checking for invalid numbers and add continue to the checks for invalid numbers. So the last lines would end up like this:
if data == 999:
break
elif data >= 100:
print("error in value")
continue
elif data <= 0:
print("error in value")
continue
average = round(total) / count

Counting Grades to print

Hopefully this will be very simple all I need help with is getting a count of the letter grades and then printing them along with the list.
Here is my code:
def getScores():
f_obj = open("scores.txt", "r")
data = f_obj.readlines() #read file into a list of record strings
f_obj.close()
return data
def displayData(data):
print("Name Avg Grade")#print headings
for record in data:
name, ex1, ex2, ex3 = record.split()
exam1 = float(ex1)
exam2 = float(ex2)
exam3 = float(ex3)
avg = round(exam1 + exam2 + exam3) / 3
if avg >= 100:
letterGrade = "A"
elif avg >= 89:
letterGrade = "B"
elif avg >= 79:
letterGrade = "C"
elif avg >= 69:
letterGrade = "D"
elif avg >= 59:
letterGrade = "F"
Just above here is where im stuck I cannot figure out how to do a count with the certain letter grades.
print("%-10s %5s %5s" % (name, round(avg, 1), letterGrade))
print()
print(
def addStudent():
name = input("Enter student name: ")
ex1 = int("Enter Exam 1 grade: ")
ex2 = int("Enter Exam 2 grade: ")
ex3 = int("Enter Exam 3 grade: ")
return name + "\t" + ex1 + "\t" + ex2 + "\t" + ex3
def storeData(data):
f_obj = open("scores.txt", "w")
f_obj.writelines(data)
f_obj.close()
def main():
scoreData = getScores() # read data file into a list
while True:
print("""
Program Options
1.) Display Students.
2.) Add a new student:
3.) Exit Program """)
option = input("Enter option 1, 2, or 3: ")
if option == "1":
displayData(scoreData)
elif option == "2":
scoreData.append(addItem()) # add record string to our list
elif option == "3":
storeData(scoreData)
print("Good bye.")
break
else:
print("Not a valid entry. Please enter 1, 2, or 3.")
main() # start the program
Hint: you already know how to determine if a grade is an A, B, C, etc. So all you need to do is increment a counter at the same time.
For example, you'd add in something like this to count the number of A grades:
if avg >= 100:
letterGrade = "A"
numAs += 1
Then do the same thing for each other grade type. Since this appears to be homework, I'll let you figure out how to do all this. Most importantly, even though Python isn't strict about this, think about the correct place to declare the counter variables.
Once you've got that working, here's an "extra credit" assignment: see if you can do all that using just a single array.

Resources