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
Related
I want my program to take any number of scores from any number of students, and run calculations on them.
student_number = 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
while more_student == "Yes":
student_number = student_number + 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
print("done")
Instead of print("done"), I want to somehow take every input I have received and be able to split it up by student, example output:
Student _ has 4 scores. Their average score is _.
Student _ has 3 scores. Their average score is _.
i'd use a dictionary i guess ? This will allow to collect data for each student, namely.
scores = {}
student = input("Student ? ") # Ask for student
if(student not in scores.keys()): # Create new student if necessary
scores[student] = []
score = int(input("Score ? ")) # Generate & store score for the student
scores[student].append(score)
Then to compute for each student the mean of the scores ... So many possibilities. The easiest one to me:
for student, score_list in scores.items():
nb_scores = len(score_list)
mean_score = sum(score_list)/len(score_list)
print("Student {} had {} scores, with a mean of {}". format(student, nb_scores, mean_score))
I'd just finished typing this up for another question of yours that got deleted -- it looks like the same basic problem as this one.
The approach in a nutshell (as I see the accepted answer to this version of the question is already doing) is to use two nested loops, breaking them when it's time to go to the outer loop.
scores = []
while True:
scores.append([])
while True:
try:
score = int(input(
f"Please enter Student {len(scores)}'s score (-1: Exit): "
))
if score == -1:
break
scores[-1].append(score)
except ValueError:
print("The score entered is not a number. Please enter it again.")
if input("Any more student? (Yes or No): ").lower() != "yes":
break
print(scores)
Please enter Student 1's score (-1: Exit): 78
Please enter Student 1's score (-1: Exit): 34
Please enter Student 1's score (-1: Exit): -1
Any more student? (Yes or No): yes
Please enter Student 2's score (-1: Exit): 45
Please enter Student 2's score (-1: Exit): -1
Any more student? (Yes or No): No
[[78, 34], [45]]
I included two infinite loops that breaks when -1 is entered. A hashmap is used where every Student ID is a key and is initialized with an empty array that stores the marks as the second loop executes itself.
marks = {}
while True:
i = int(input("Enter Student ID or press -1 to exit"))
if i == -1:
break
else:
marks[i] = []
while True:
x = int(input("Enter Mark or press -1 to exit"))
if x!=-1:
marks[i].append(x)
else:
break
for i in marks.keys():
count = len(marks[i])
avg = sum(marks[i])/count
print("Student {} has {} scores. Their average is {}".format(i, count, avg))
Create a program that will calculate a student’s grade in a class that uses a weighted grade scale.
I have to be able to manually enter each Quiz, Test, Participation, and Project Grade. It's my first year learning Python at all, and it is my first language! Thanks for the help!
Edit: Right now the code is giving me this:
"
John Doe
John Doe , You made a function letter_grade at 0x7f4424330dd0"
name="John Doe"
print(name)
#Entering Particiaption Grade and Weight
def Participation(Participation1):
Participation1= int(input())
participation_average=int(input(Participation1/1))
return participation_average
def ParticipationW(ParticipationWeight):
ParticipationWeight = int(input())
return ParticipationWeight
#Entering Quiz Grades and Weight
def Quiz(Quiz1, Quiz2, Quiz3, Quiz4, Quiz5, Quiz6):
Quiz1 = int(input())
Quiz2 = int(input())
Quiz3 = int(input())
Quiz4 = int(input())
Quiz5 = int(input())
Quiz6 = int(input())
quiz_average=int(input((Quiz1+Quiz2+Quiz3+Quiz4+Quiz5+Quiz6)/6))
return quiz_average
def QuizW(QuizWeight):
QuizWeight = int(input())
return QuizWeight
#Projects
def Project(Project1, Project2, Project3, Project4, Project5, Project6):
Project1 = int(input())
Project2 = int(input())
Project3 = int(input())
Project4 = int(input())
Project5 = int(input())
Project6 = int(input())
project_average=int(input((Project1+Project2+Project3+Project4+Project5+Project6)/6))
return project_average
def ProjectW(ProjectWeight):
ProjectWeight = int(input())
return ProjectWeight
#Enter Test Grades and Variables
def Test(Test1, Test2, Test3, Test4):
Test1 = int(input())
Test2 = int(input())
Test3 = int(input())
Test4 = int(input())
test_average=int(input((Test1+Test2+Test3+Test4)/4))
return test_average
def TestW(TestWeight):
TestWeight = int(input())
return TestWeight
def letter_grade(FinalGrade):
FinalGrade=int(input((Participation * ParticipationW) + (Quiz * QuizW) + (Project * ProjectW) + (Test* TestW)))
if FinalGrade >= 90:
return "You made a A!"
elif FinalGrade >= 80:
return "You made a B!"
elif FinalGrade >= 70:
return "You made a C!"
elif FinalGrade >= 60:
return "You made a D!"
else:
return "Sorry, you failed."
print(name, ", You made a", letter_grade, ".")
This is what he has given us so far:
Enter Student Name:
Please enter the total possible quiz grade:60
Please enter quiz weight in decimal form:.15
Please enter the first quiz grade:10
Please enter the second quiz grade:5
Please enter the third quiz grade:6
Please enter the fourth quiz grade:7
Please enter the fifth quiz grade:10
Please enter the sixth quiz grade:9
Please enter the total possible Participation grade:100
Please enter participation weight in decimal form:.05
Please enter the Participation grade:100
Please enter the total possible project grade:600
Please enter project weight in decimal form:.50
Please enter the first project grade:100
Please enter the second project grade:100
Please enter the third project grade:90
Please enter the fourth project grade:80
Please enter the fifth project grade:80
Please enter the sixth project grade:50
Please enter the total possible test grade:400
Please enter test weight in decimal form:.30
Please enter the first test grade:100
Please enter the second test grade:90
Please enter the third test grade:80
Please enter the fourth test grade:50
Jon Doe's grades are:
Overall Quiz Grade: 11.75
Overall Participation Grade: 5.0
Overall Project Grade: 41.66666666666667
Overall Test Grade: 24.0
Final Grade: 82.41666666666667
Your Grade: B
Here is your answer dear all the best and welcome to Python
Code
name=input("Enter your name:")
def grade():
#Entering Particiaption Grade and Weight
Participation1= int(input("Entering Particiaption Grade :"))
participation_average=Participation1
ParticipationWeight = int(input("Entering Particiaption Weight:"))
#Entering Quiz Grades and Weight
Quiz1 = int(input("Enter Quiz 1 Grades:"))
Quiz2 = int(input("Enter Quiz 2 Grades:"))
Quiz3 = int(input("Enter Quiz 3 Grades:"))
Quiz4 = int(input("Enter Quiz 4 Grades:"))
Quiz5 = int(input("Enter Quiz 5 Grades:"))
Quiz6 = int(input("Enter Quiz 6 Grades:"))
quiz_average=(Quiz1+Quiz2+Quiz3+Quiz4+Quiz5+Quiz6)/6
QuizWeight = int(input("Enter Quiz weight:"))
#Projects
Project1 = int(input("Enter Project 1 Grades:"))
Project2 = int(input("Enter Project 2 Grades:"))
Project3 = int(input("Enter Project 3 Grades:"))
Project4 = int(input("Enter Project 4 Grades:"))
Project5 = int(input("Enter Project 5 Grades:"))
Project6 = int(input("Enter Project 6 Grades:"))
project_average=(Project1+Project2+Project3+Project4+Project5+Project6)/6
ProjectWeight = int(input("Enter Project Weight:"))
#Enter Test Grades and Variables
Test1 = int(input("Enter Test 1 Grades:"))
Test2 = int(input("Enter Test 2 Grades:"))
Test3 = int(input("Enter Test 3 Grades:"))
Test4 = int(input("Enter Test 4 Grades:"))
test_average=(Test1+Test2+Test3+Test4)/4
TestWeight = int(input("Enter Test Weight:"))
FinalGrade=(participation_average* ParticipationWeight) + (quiz_average* QuizWeight) + ( project_average * ProjectWeight) + (test_average* TestWeight)
print("Dear ",name,",")
if FinalGrade >= 90:
print("You made a A!")
elif FinalGrade >= 80:
print( "You made a B!")
elif FinalGrade >= 70:
print("You made a C!")
elif FinalGrade >= 60:
print("You made a D!")
else:
print("Sorry, you failed.")
grade()
I'm a beginner in python. I have created a database for student in python. I'm not able to get the output for all iterations in dict.
my source code:-
n = int(raw_input("Please enter number of students:"))
student_data = ['stud_name', 'stud_rollno', 'mark1', 'mark2','mark3','total', 'average'] for i in range(0,n):
stud_name=raw_input('Enter the name of student: ')
print stud_name
stud_rollno=input('Enter the roll number of student: ')
print stud_rollno
mark1=input('Enter the marks in subject 1: ')
print mark1
mark2=input('Enter the marks in subject 2: ')
print mark2
mark3=input('Enter the marks in subject 3: ')
print mark3
total=(mark1+mark2+mark3)
print"Total is: ", total
average=total/3
print "Average is :", average
dict = {'Name': stud_name, 'Rollno':stud_rollno, 'Mark1':mark1, 'Mark2':mark2,'Mark3':mark3, 'Total':total, 'Average':average} print "dict['Name']: ", dict['Name'] print "dict['Rollno']: ", dict['Rollno'] print "dict['Mark1']: ", dict['Mark1'] print "dict['Mark2']: ", dict['Mark2'] print "dict['Mark3']: ", dict['Mark3'] print "dict['Total']: ", dict['Total'] print "dict['Average']: ", dict['Average']
if i give no of students as 2, I'm getting dict for 2nd database only and not for 1st one too.
output that i got
Please enter number of students:2
Enter the name of student: a
a
Enter the roll number of student:1
1
Enter the marks in subject 1:1
1
Enter the marks in subject 2:1
1
Enter the marks in subject 3:1
1
Total is:3
Average is :1
Enter the name of student:b
b
Enter the roll number of student:2
2
Enter the marks in subject 1:2
2
Enter the marks in subject 2:2
2
Enter the marks in subject 3:2
2
Total is:6
Average is :2
dict['Name']:b
dict['Rollno']:2
dict['Mark1']:2
dict['Mark2']:2
dict['Mark3']:2
dict['Total']:6
dict['Average']:2
Your current code overwrites dict for every i. In addition, you shouldn't use the name dict as this causes confusion with the data type dict in Python.
One solution for you is to use a list of dictionaries, something like the following:
n = int(raw_input("Please enter number of students:"))
all_students = []
for i in range(0, n):
stud_name = raw_input('Enter the name of student: ')
print stud_name
stud_rollno = input('Enter the roll number of student: ')
print stud_rollno
mark1 = input('Enter the marks in subject 1: ')
print mark1
mark2 = input('Enter the marks in subject 2: ')
print mark2
mark3 = input('Enter the marks in subject 3: ')
print mark3
total = (mark1 + mark2 + mark3)
print"Total is: ", total
average = total / 3
print "Average is :", average
all_students.append({
'Name': stud_name,
'Rollno': stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average': average
})
for student in all_students:
print '\n'
for key, value in student.items():
print '{0}: {1}'.format(key, value)
By adding the responses for each new student onto the end of the list, we track all of them in turn. Finally, we print them out using the keys and values stored in the dictionary. This prints, with your inputs:
Name: a
Rollno: 1
Average: 1
Mark1: 1
Mark2: 1
Mark3: 1
Total: 3
Name: b
Rollno: 2
Average: 2
Mark1: 2
Mark2: 2
Mark3: 2
Total: 6
stud = {}
mrk = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER STUDENT INFORMATION ------------------------ ")
while True :
rno = int(input("enter roll no.. :: -- "))
if rno == 0 :
break
else:
for i in range(3):
print("enter marks ",i+1," :: -- ",end = " ")
n = int(input())
mrk.append(n)
stud[rno] = mrk
mrk = []
print("Records are ------ ",stud)
print("\nRollNo\t Mark1\t Mark2\t Mark3\t Total")
tot = 0
for r in stud:
print(r,"\t",end=" ")
for m in stud[r]:
tot = tot + m
print(m,"\t",end=" ")
print(tot)
tot = 0
name1 = input("What is your first name: ")
name2 = input("What is your last name: ")
grades = []
prompt = "Enter your grade or enter '1234' to get your letter grade and average: "
print('Please enter your grades:')
grade1 = input(prompt).strip()
while (prompt != 1234):
grades.append(grade1)
grade1 = input(prompt).strip()
else:
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
I need this to print out the name and average. When I input '1234' it just goes on normally. Can you help me so it makes it output the else statement? Thanks.
This is one problem:
while (prompt != "1234"):
You're comparing the prompt (which is "Enter your grade...") to the number 1234, and the prompt never changes. Which means it will never be equal to 1234, so it will go on forever! I believe you want to compare to grade1, rather than prompt.
Another issue, is the else statement:
else:
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
You don't need the else statement, because you want those statements to be executed after the while loops ends, right? Then just put them after the while loop. No need for an if or if-else statement!
With those corrections, the code will look similar to this:
name1 = input("What is your first name: ")
name2 = input("What is your last name: ")
grades = []
prompt = "Enter your grade or enter '1234' to get your letter grade and average: "
print('Please enter your grades:')
grade1 = input(prompt).strip()
while (grade1 != "1234"):
grades.append(grade1)
grade1 = input(prompt).strip()
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
Only a few syntax errors were holding you back, so keep up the good work!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Just a beginner at Python trying to make a GPA calculator as a basic project, but getting an error in syntax: "expected an indented block"
import keyword
classes = int(input("How many classes do you need to calculate?: "))
gpa = 0.0
if classes == 1:
credits = int(input("Please enter the amount of credit hours of the class: "))
grade = input("What was the grade you have earned?: ")
letter_points = letterGradeConversion()
print(letter_points)
elif classes == 2:
credits = int(input("Please enter the amount of credit hours of the first class: "))
grade = input("What was the grade you have earned?: ")
credits = int(input("Please enter the amount of credit hours of the second class: "))
grade = input("What was the grade you have earned?: ")
elif classes == 3:
credits = int(input("Please enter the amount of credit hours of the first class: "))
grade = input("What was the grade you have earned?: ")
credits = int(input("Please enter the amount of credit hours of the second class: "))
grade = input("What was the grade you have earned?: ")
credits = int(input("Please enter the amount of credit hours of the third class: "))
grade = input("What was the grade you have earned?: ")
elif classes == 4:
credits = int(input("Please enter the amount of credit hours of the first class: "))
grade = input("What was the grade you have earned?: ")
credits = int(input("Please enter the amount of credit hours of the second class: "))
grade = input("What was the grade you have earned?: ")
credits = int(input("Please enter the amount of credit hours of the third class: "))
grade = input("What was the grade you have earned?: ")
credits = int(input("Please enter the amount of credit hours of the fourth class: "))
grade = input("What was the grade you have earned?: ")
else:
print("The max number of classes on this application is currently 4")
def letterGradeConversion():
if grade == A:
gpa = gpa + 4
elif grade == B:
gpa = gpa + 3
elif grade == C:
gpa = gpa + 2
elif grade == D:
gpa = gpa + 1
elif grade == F:
gpa = gpa + 0
else:
print("That is not a valid letter grade")
Not in code:
iuashd;alksdjas;kjdha;slkjaskljsakdljas;ljlkjf;lkjsFLKAJSD;KJASD;KLk;jaS'LKDJ;ldjk;'DH'AHKL'ASJKLASJKQIOWJWQOIH
Your function definition (everything after def ... :) has to be indented.
So
def letterGradeConversion():
if grade == A:
gpa = gpa + 4
...
instead of
def letterGradeConversion():
if grade == A:
gpa = gpa + 4
...
The entire block function definition for letterGradeConversion needs to be indented. Take a look at Python docs on indentation - https://docs.python.org/2.3/ref/indentation.html