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
Related
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!
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]))
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
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
Why is this while loop not ending when the proper input is entered (a number between 0 and 100)
grade = 110
invalid_input = 1
while grade< 0 or grade> 100:
if invalid_input >=2:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
grade= raw_input("Please enter your marks for Maths : ")
invalid_input +=1
what ever i put in be it a number or text the (this is an invalid entry , Please enter a number between 0 and 100
does anyone one know what is wrong?
your grade should be cast to an int. Otherwise, since it's a string, the while condition will always remain satisfied.
Also, you can just as easily (and perhaps more cleanly) use a boolean for invalid_input:
invalid_input = True
while invalid_input:
grade = int(raw_input("enter data"))
if grade >= 0 and grade <= 100:
invalid_input = False
else:
print "Please try again"
in grade=raw_input("Please enter your marks for Maths : "), grade is a string, not number. try
grade = int(raw_input("Please enter your marks for Maths : "))
In order to prevent the program from being terminated if the user makes a wrong input, you will need to use a exceptions, like this
grade = 110
invalid_input = 1
while grade< 0 or grade> 100:
if invalid_input >=2:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
try:
grade= int(raw_input("Please enter your marks for Maths : "))
except ValueError:
grade = -1 # just to enter another iteration
invalid_input +=1