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]}")
Related
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
How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. Entering Male and Female for a gender argument. I'm using this Python code:
def mean(values):
length = len(values)
total_sum = 0
for i in range(length):
total_sum += values[i]
total_sum = sum (values)
average = total_sum*1.0/length
return average
name = " "
Age = " "
Gender = " "
people = []
ages = []
while name != "":
### This is the Raw data input portion and the ablity to stop the program and exit
name = input("Enter a name or type done:")
if name == 'done' : break
Age = int(input('How old are they?'))
Gender = input("What is their gender Male or Female?")
### This is where I use .append to create the entry of the list
people.append(name)
people.append(Age)
ages.append(Age)
people.append(Gender)
### print("list of People:", people)
#### useing the . count to call how many m of F they are in the list
print ("Count for Males is : ", people.count('Male'))
print ("Count for Females is : ", people.count('Female'))
### print("There ages are",ages)
### This is where I put the code to find the average age
x= (ages)
n = mean(x)
print ("The average age is:", n)
I would like to also force an age in the 18-25 range.
"... that forces them to reenter until it is correct?... "
Since you also asked for a way to re-enter, the following snippet uses an escape sequence of the form \033[<N>A which moves the cursor up N lines and the Carriage Return escape sequence, \r, to print over the invalid data and take input again.
import sys
age = 0
gender = ""
agePrompt = "How old are they? "
genderPrompt = "What is their gender Male or Female? "
#Input for age
print("")
while not ( 18 <= age <= 25 ):
sys.stdout.write( "\033[1A\r" + " " * (len(agePrompt) + len(str(age))) )
sys.stdout.write( "\r" + agePrompt )
sys.stdout.flush()
age=int(input())
#Input for gender
print("")
while not ( gender == "Male" or gender == "Female" ) :
sys.stdout.write( "\033[1A\r" + " " * (len(genderPrompt) + len(str(gender))) )
sys.stdout.write( "\r" + genderPrompt )
sys.stdout.flush()
gender=str(input())
Another solution would be to use the escape sequence of the form \033[<N>D which moves the cursor backward N columns.
Simply use a while operator that continues until you have satisfied the condition you wish be satisfied.
Gender = ""
while Gender != "Male" or Gender != "Female":
Gender = raw_input("What is your gender, Male or Female?")
Just keep looping until they give a valid input. Do the same for the gender.
Age = ""
while True:
Age = int(input('How old are they?'))
if int(Age) >= 18 and int(Age) <= 25:
break
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
python 3.3.3
I am trying to write a program for class and I am lost. Here is what I need to do.
I need to calculate an average per student based on grades entered.
I need to calculate a class average.
if a student enters a grade of -1 input of grades stop.
need to print a message with each students grade.
the students grade should show a numeric grade and a letter grade.
the message will be based off of the students letter grade.
how do i collect and store students name and test grades.
so that i can output it all at once to where it will show the students name.
thier numeric average, a letter grade based off that average,
and a statement based off the letter grade they recieved?
heres the code i have so far:
def main():
another_student = 'y'
while another_student == 'y' or another_student == 'Y':
student_average()
print()
another_student = input('do you have another student to enter (y/n) ? ')
while another_student == 'n' or another_student == 'N':
student_average_list()
class_average()
break
def student_average():
total = 0.0
print()
student_name = input('what is the students name? ')
print()
print()
print(student_name)
print('-------------------')
number_of_tests = int(input('please enter the number of tests : '))
for test_num in range(number_of_tests):
print('test number', test_num + 1, end='')
score = float(input(': '))
total += score
student_average = total / number_of_tests
print ()
print(student_name,"'s average is : ",student_average, sep='')
def student_average_list():
print ('kahdjskh')
def class_average():
print ('alsjd')
main()
I think this is close to what you're basically looking for. It defines aStudentclass to make data storage and processing a little easier to manage.
class Student(object):
def __init__(self, name):
self.name, self.grades = name, []
def append_grade(self, grade):
self.grades.append(grade)
def average(self):
return sum(self.grades) / len(self.grades)
def letter_grade(self):
average = self.average()
for value, grade in (90, "A"), (80, "B"), (70, "C"), (60, "D"):
if average >= value:
return grade
else:
return "F"
def main():
print()
print('Collecting class student information')
a_class = [] # "class" by itself is a reserved word in Python, avoid using
while True:
print()
print('{} students in class so far'.format(len(a_class)))
another_student = input('Do you have another student to enter (y/n) ? ')
if another_student[0].lower() != 'y':
break
print()
student_name = input('What is the student\'s name? ')
a_class.append(Student(student_name))
print()
print('student :', student_name)
print('-------------------')
number_of_tests = int(input('Please enter the number of tests : '))
for test_num in range(1, number_of_tests+1):
print('test number {}'.format(test_num), end='')
score = float(input(' : '))
if score < 0: # stop early?
break
a_class[-1].append_grade(score) # append to last student added
print_report(a_class)
def print_report(a_class):
print()
print('Class Report')
print()
for student in sorted(a_class, key=lambda s: s.name):
print('student: {:20s} average test score: {:3.2f} grade: {}'.format(
student.name, student.average(), student.letter_grade()))
print()
print('The class average is {:.2f}'.format(class_average(a_class)))
def class_average(a_class):
return sum(student.average() for student in a_class) / len(a_class)
main()
You need to keep a list of marks for the whole class. student_average function is doing too many things. Maybe make a function get_student_marks that just returns the list of a student's marks. You'd need an average function to compute the average of a list, which you could use for both student average and class average. Good luck!