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.
Related
I am a beginner in python, working on some code, this is the code I have so far and I don't know how to do it on here. so far I made a code about input the students' score from the user and print pass or retake. and now I am trying to print the highest Korean score with the name and index. and I want to know is there any way to print the name who got the highest score with index(ex. if Kira got the highest score than should be printed like: '3: Kira got the highest score on the Korean test.') How can I make this work? I searched up the internet and tried several ways but still doesn't work so I ask here..
students = ['Anna', 'Elsa', 'Kira']
korean = []
math = []
for i, name in enumerate(students,1):
print('{}: {}'.format(i, name))
for stu in students:
for y in range(1):
kscore = int(input("Enter {}'s korean score: ".format(stu)))
for x in range(1):
mscore = int(input("Enter {}'s math score: ".format(stu)))
if kscore <= 50 and mscore <= 70:
print("You need to retake both")
elif kscore <= 50:
print("You need to retake Korean")
elif mscore <= 70:
print("You need to retake Math")
else:
print("You are pass")
korean.append(kscore)
math.append(mscore)
print('{}: {} got the highest score on the Korean test.'.format(i, name, max(korean)))
You needed to get the index of the maximum score take that index to get the person's name.
Here is the full code:
P.S: I changed some things because they were not efficient.
students = ['Anna', 'Elsa', 'Kira']
korean = []
math = []
for i, name in enumerate(students, 1):
print('{}: {}'.format(i, name))
for stu in students:
kscore = int(input("Enter {}'s korean score: ".format(stu)))
mscore = int(input("Enter {}'s math score: ".format(stu)))
if kscore <= 50 and mscore <= 70:
print("You need to retake both")
elif kscore <= 50:
print("You need to retake Korean")
elif mscore <= 70:
print("You need to retake Math")
else:
print("You are pass")
korean.append(kscore)
math.append(mscore)
person = students[korean.index(max(korean))]
print('{}: {} got the highest score on the Korean test.'.format(i, person))
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)
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
Here is the scenario:
Ask the user for a number which must be between 20 and 30. The user and the computer take it in turns to subtract 1, 2 or 3 from the current value. The last player to subtract a value loses.
Here's what I have so far
import random
while True:
count = int(input("Enter a number between 20 and 30"))
if count < 20 or count > 30:
print("That number is not in range")
else:
print("\nLet's play")
print("\nSubtract 1, 2, or 3 from", count)
# Player moves
def playermove():
while True:
number = int(input("\nWhat number would you like to subtract"))
if number > 1 and number <4:
print("\nyou subtracted", number, "there is", count-number, "left")
print("\nMy turn!")
break
else:
print("\nplease enter 1,2 or 3")
def computermove():
computernum = random.randint(1,3)
print("\nI subtracted", computernum, "there is", count-computernum, "left")
print("\nMake your move")
Get the initial count from the user something like this:
def get_count():
count = 0
while count < 20 or count > 30:
count = int(input("Enter a number between 20 and 30"))
if count < 20 or count > 30:
print("That number is not in range")
else:
return count
count = get_count()
Next, start playing the game.
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.