Counting Grades to print - python-3.x

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.

Related

Python multiply game. My script needs to have a arbitrarily number of players that each have to take turn in answering a multiplication question

Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break

python accumulating while loop keeps repeating what did i do wrong?

I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
while leftOrRight != "X":
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:
leftOrRight = None
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
According to your code you are not changing the value for leftOrRight after entering the loop so the condition for your while loop is never false I would suggest the following edit:
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = '' #anything random
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
so that you get a prompt every time the loop is executed and you can click X to exit
Your program just got the character that had the largest id in the ascii table.
And only doing the first string as the longString = max(n) wasn't even in the while loop.
also max returns the largest value, so in this case it was just converting the text into an ascii number.
instead you should use len(string) which returns the length of the string.
Unlike max() which is used like:
11 == max(11,10,1,2) as 11 is the largest character.
n = (input("Input: ")) #get initial input
longest = 0 #define the varible which we will keep the length of the longest string in
longest_str = "" #define the varible which stores the value of the longest string.
while n: #you don't need that other stuff, while n does the same as while n != ''
n = str(input("Input: ")) #get input
length = len(n) #gets the length of the input
if length > longest: #if the length of our input is larger than the last largest string
longest = length #set the longest length to current string length
longest_str = n #set the longest string to current string
#once the user hits enter (typing "") we exit the while loop, and this code runs afterwards.
print("Longest input was", longest_str, "at", longest, "characters long")
Because there are two specific counts we are accumulating for, and the outlying char is at the end of our input, we can set our while to True to break when we hit a char other that "L" or "R".
leftOrRight = ""
# Write your loop here.
while True:
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
if leftOrRight == "L":
leftTotal = leftTotal + 1
elif leftOrRight == "R":
rightTotal = rightTotal + 1
else:
break
# Output number of left or right-handed students.
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))

not printing count or average regardless of indentation

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)

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.

Resources