How to turn a 2dimensional program into 1dimensional? - python

My professor asked me to make a two-dimensional program that would count a student's average. Now he said he wants me to turn my hardwork into a one dimensional program and I have no idea how to do so, any help?
import sys
students = []
grades = []
while True:
student = input ("Enter a name: ").replace(" ","")
if student.isalpha() == True and student != "0":
while True:
grade = input("Enter a grade: ").replace(" ","")
if grade == "0" or grade == 0:
print ("\n")
print ("A zero is entered.")
sys.exit(0)
if grade.isdigit()== True:
grade = int(grade)
if grade >= 1 and grade <= 10:
if student in students:
index = students.index(student)
grades[index].append(grade)
break
else:
students.append(student)
grades.append([grade])
break
else:
print("Invalid grade.")
elif student == "0":
print("A zero is entered.")
break
else:
print ("Invalid name.")
for i in range(0,len(students)):
print("NAME: ", students[i])
print("GRADE: ", grades[i])
print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")
For example, right now it prints out:
NAME: Jack
GRADE: [8, 7, 9]
AVERAGE: 8.0
But I need it to print out like this:
NAME: Jack
GRADE: 8, 7, 9
AVERAGE: 8.0

I think that replacing grades.append([grade]) with grades.append(grade) would help.
Okay, I think I understand your question better now. Try printing like this:
print("GRADE: ", ", ".join(grades[i]))

Related

GPA Calculator + failure testing

My code is only inputting one print command when there are two that need to be put out. I know this problem is simple but I need a new perspective
here is my code:
name = input("What is your name? \n")
h1 = ("Class Name")
h2 = ("Class Grade")
h3 = ("Credit Hours")
point = input("\nEnter your class name followed by your letter grade and hours (say Done to stop input):\n")
class_data = []
while point != "Done":
words = point.split(" ")
if len(words) == 1:
print("Error: No spaces in string. Try again.")
elif len(words) > 4:
print("Error: Too many spaces in input. Try again. ")
else:
try:
class_name = words[0]
grades = (words[1])
hrs = int(words[2])
print("Name of class:", class_name)
print("Grade:", grades)
print("Class Hours:", hrs)
class_data.append((class_name, grades, hrs,))
except ValueError:
print("Error: Space not followed by an integer.")
point = input("\nEnter your class name followed by your letter grade and hours (say Done to stop input):\n")
def gpa_calculator(grades):
points = 0
i = 0
grade_c = {"A":4,"A-":3.67,"B+":3.33,"B":3.0,"B-":2.67, "C+":2.33,"C":2.0,"C-":1.67,"D+":1.33,"D":1.0,"F":0}
if grades != class_data:
for grade in grades:
points += grade_c[item[1]]
gpa = points / len(class_data)
return gpa
else:
return None
print("Name: ", name)
print("-" * 66)
print("%-17s|%13s|%7s|" % (h1, h2, h3))
print("-" * 66)
for item in class_data:
print("%-17s|%13s|%12s|" % (item[0], item[1], item[2]))
print("-" * 66)
print('Your projected GPA is: ',(gpa_calculator(grades)))
print("-" * 66)
if item[0] == "Computer-Science" and item[1] == "D":
print ("failing CS")
if item[0] == "Programming" and item[1] == "D":
print ("failing programming")
what i need help with are the last four lines
output:
What is your name?
Nich
Enter your class name followed by your letter grade and hours (say Done to stop input):
Programming D 10
Name of class: Programming
Grade: D
Class Hours: 10
Enter your class name followed by your letter grade and hours (say Done to stop input):
Computer-Science D 10
Name of class: Computer-Science
Grade: D
Class Hours: 10
Enter your class name followed by your letter grade and hours (say Done to stop input):
Done
Name: Nich
------------------------------------------------------------------
Class Name |Class Grade|Credit Hours|
------------------------------------------------------------------
Programming | D| 10|
Computer-Science| D| 10|
------------------------------------------------------------------
Your projected GPA is: 0.5
------------------------------------------------------------------
failing CS
I've tried elif and true commands this is the closest I've been to solving this.
You need another loop, like the one you used to print the grade table.
for item in class_data:
if item[1] in ("D", "F"):
print(f"failing {item[0]}")

output combines scores from all students instead of just the one list after repeat

Where am I going wrong, the first part does exactly what I want. I put the first student in with scores it converts and averages but after repeat, it combines the lists and averages ofoutput all subsequent students.
def determine_grade(score):
if (score > 89):
return "A"
elif (score > 79):
return "B"
elif (score > 69):
return "C"
elif (score > 59):
return "D"
elif (score <= 59):
return "F"
def calc_average(test_scores):
total = 0
for i in range(len(test_scores)):
total = total + test_scores[i]
return total/int(len(test_scores))
def main():
repeat="yes"
test_scores = []
while repeat.lower() == "yes":
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter anther student? yes or no: ")
main()
The thing that is wrong with this piece of code is that when you finished collecting info from one student the info is still left in the list, and was mixed up with another student's info
def main():
repeat="yes"
test_scores = []
while repeat.lower() == "yes":
test_scores.clear()
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter another student? yes or no: ")
main()
You need to clear the list before collecting again.
After this line:
while repeat.lower() == "yes":
put:
print(test_scores)
Run the script and enter marks for a couple of students.
I think you will see why it is summing all the students marks in one go.
By the way, sum(test_scores) will add up the elements of test_scores for you. No need
for a loop. Also try out:
for score in test_scores:
print(score)
In general, when you are tempted to write
for i in range(len(things)):
followed by
things[i]
inside the loop, it is usually easier to write
for thing in things:
do_something_with(thing)
Your code will be shorter, more readable and more efficient.
Replace your main fucntion with this one:
def main():
repeat="yes"
while repeat.lower() == "yes":
test_scores = [] # Inside the while loop so it is new every time
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter anther student? yes or no: ")

How to use two != breaks in program in Python?

The problem statement, all variables and given/known data
I need a program, which would break and show results once a 0 is entered in input name and input grade.
I figured how to do that in name, but how do I add another break? Like grade !="0"?
The program I have so far:
students = []
grades = []
while True:
name = input ("Enter a name: ")
if name.isalpha() == True and name != "0":
while True:
grade = input("Enter a grade: ")
if grade.isdigit()== True:
grade = int(grade)
if grade >= 1 and grade <= 10:
if name in students:
index = students.index(name)
grades[index].append(grade)
break
else:
students.append(name)
grades.append([grade])
break
else:
print("Grade is not valid. Try to enter it again!")
elif name == "0":
print("A zero is entered!")
break
else:
print ("Grade is not valid. Try to enter it again!")
for i in range(0,len(students)):
print("NAME: ", students[i])
print("GRADES: ", grades[i])
print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")
Also is there any way that I can make Python ignore spaces in input function?
Example: I enter a grade that has "________8" in it (_ are spaces) and the program does not want to ignore it, how do I make it ignore the spaces and just accept the number as it is?
strip() method
Use strip() method of string to strip the white spaces.
Demo:
>>> a = " Go "
>>> a.strip()
'Go'
>>> a.rstrip()
' Go'
>>> a.lstrip()
'Go '
>>>
Your code will work fine. Produce correct output.
Use dictionary to save Student records.
Demo:
import collections
student_record = collections.defaultdict(list)
while True:
name = raw_input("Enter a name: ").strip()
if name=="0":
print "A zero is entered!"
break
if not name.isalpha():
print "Name is no valid. Try again. Enter alpha value only."
continue
while True:
grade = raw_input("Enter a grade: ").strip()
if grade.isdigit():
grade = int(grade)
if 1<=grade <= 10:
student_record[name].append(grade)
break
else:
print "Grade is not valid. Try again. Enter digit values between 1 and 10."
else:
print "Grade is not valid. Try again. Enter digit values."
for i, j in student_record.items():
print "\nNAME: ", i
print "GRADES: ", j
print "AVERAGE: ", round(sum(j)/len(j),1)
Output:
$ python test1.py
Enter a name: ABC
Enter a grade: 2
Enter a name: XYZ
Enter a grade: 5
Enter a name: ABC
Enter a grade: 6
Enter a name: 0
A zero is entered!
NAME: XYZ
GRADES: [5]
AVERAGE: 5.0
NAME: ABC
GRADES: [2, 6]
AVERAGE: 4.0
Note:
Use raw_input() for Python 2.x
Use input() for Python 3.x

How to remove brackets in python with string?

I have this program:
import sys
students = []
grades = []
while True:
student = input ("Enter a name: ").replace(" ","")
if student.isalpha() == True and student != "0":
while True:
grade = input("Enter a grade: ").replace(" ","")
if grade == "0" or grade == 0:
print ("\n")
print ("A zero is entered.")
sys.exit(0)
if grade.isdigit()== True:
grade = int(grade)
if grade >= 1 and grade <= 10:
if student in students:
index = students.index(student)
grades[index].append(grade)
break
else:
students.append(student)
grades.append([grade])
break
else:
print("Invalid grade.")
elif student == "0":
print("A zero is entered.")
break
else:
print ("Invalid name.")
for i in range(0,len(students)):
print("NAME: ", students[i])
print("GRADE: ", grades[i])
print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")
I need to make the [] disappear between numbers when the program prints them, for example.
When you enter numbers, like this:
Enter a name: Jack
Enter a grade: 8
Enter a name: Jack
Enter a grade: 9
Enter a name: Jack
Enter a grade: 7
Enter a name: 0
A zero is entered.
It prints like this:
NAME: Jack
GRADE: [8, 9, 7]
AVERAGE: 8.0
But I need the program to print like this:
NAME: Jack
GRADE: 8, 9, 7
AVERAGE: 8.0
The grades should be without brackets.
I think I need to use string or something, does anyone know how?
strip allows you to remove the specified characters from the beginning and from the end.
str(grades[i]).strip('[]')
First:
>>> grades = [[1,2,3],[4,5,6]]
Now you have a few choices:
>>> print("GRADE:", *grades[0])
GRADE: 1 2 3
or:
>>> print("GRADE:", ', '.join(map(str, grades[0])))
GRADE: 1, 2, 3
or, in a script or block:
print("GRADE: ", end='')
print(*grades[0], sep=', ')
result of above:
GRADE: 1, 2, 3
Replace [0] with [i] as needed.
If grades is a list of lists of integers:
print(', '.join(str(i) for i in grades[g])) # where g sublist index

Loop Python Script

Im new to python and I am currently working on a python script and want to add a loop at the end of it, currently the code is as follows:
#FinalGrade
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
Id like to find out if it would be possible to set a loop so another student can be entered, would this be possible?
Thank you
Why not put it in an infinite loop?
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
...
cont = input('Do you want to keep entering students? y/n: ')
Or if you want to keep all of the results:
results = []
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
...
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
...
cont = input('Do you want to keep entering students? y/n: ')
And you can just loop through the results to see them.
You mean just one more student to be entered?
You can probably do that with a while or for loop. Something along these lines:
counter = 0
while (counter < 2):
your existing code
....
counter += 1

Categories