我一直试图让这个程序工作,它运行,但一旦我让它运行,我发现了这个问题。现在它要求输入成绩点和学分,并按预期打印出 GPA,但我可以在成绩点中输入任何内容,它会输出一个值。我想要的是仅当用户输入介于 0.0-4.0 之间的数字时,gradePoint 才能工作。我在考虑某种循环,比如 if 循环,但有没有更简单的方法(或首选方法)来做到这一点?
这是代码:
def stu():
stu = Student
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQpoints(self):
return self.qpoints
def getStudent(infoStr):
name, hours, qpoints = infoStr.split("\t")
return Student(name, hours, qpoints)
def addGrade(self, gradePoint, credits):
self.qpoints = gradePoint * credits
self.hours = credits
self.gradePoint = float(gradePoint)
self.credits = float(credits)
def gpa(self):
return self.qpoints/self.hours
def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
gradePoint = float(input("Enter Grade Point"))
if gradePoint > 4.0:
print("Please enter a Grade Point that is less then 4.")
stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)
main()
这是外壳打印输出(我知道 GPA 中重复了成绩点,这是针对一门课的,我们应该使用框架程序并更改一些东西):
Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is: 3.5
Enter Credit Hours 12
Enter Grade Point 3.2
Student GPA is: 3.2
谢谢!
编辑:我只是按照评论中的建议做了一个 if 循环,它有点工作,因为它打印出我想要的东西,但没有让它停止并等待正确的输入。我不完全确定如何让它做到这一点。
这是来自外壳的新打印:
Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is: 3.5
Enter Credit Hours 4
Enter Grade Point 4.5
Please enter a Grade Point that is less then 4.
Student GPA is: 4.5