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
Related
Basically, you input the names and they are saved to the list. Say I input "a, b, c, d and e. After printing the list it comes out with "a, a, a, a, and a"
Then, when it asks if the student has paid or not, it doesn't matter what value you input, the name won't be moved to the designated list.
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + name + " paid? Input y or n: "
input == raw_input()
if input == "y":
paid_list.append[input]
name_list.next
elif input == "n":
unpaid_list.append[input]
name_list.next
print "The students who have paid are", paid_list
print "The students who have not paid are", unpaid_list
Your populating loop is:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
You first assign the value received through raw_input to name.
Then, for count from 0 to 4, you check if name is equal to the input, and then, append it to name_list.
Instead of checking the equality by writing name == raw_input(...), what you want is to assign the input value into name.
Therefore, you mustn't use ==, but =.
Your loop should be:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
Now here is a more Pythonic way:
names_list = [] # there are more than one name in the list
for _ in range(5): # the loop index is not needed, so I use the anonymous underscore
name = raw_input("Enter the student's name: ")
names_list.append(name)
you can try:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5:
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + names + " paid? Input y or n: "
input = raw_input()
if input == "y":
paid_list.append[input]
elif input == "n":
unpaid_list.append[input]
Note: raw_input() is not there in python 3.x. Instead use: input() (documentation).
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
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]))
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
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