gpt4 book ai didi

python - 如何使 float 在 python 3 中具有特定范围(或者我可以)?

转载 作者:太空宇宙 更新时间:2023-11-03 19:19:54 25 4
gpt4 key购买 nike

我一直在尝试让这个程序运行,并且它可以运行,但是一旦我让它运行,我就发现了这个问题。现在,它会要求 GradePoint 和学时,并按预期打印出 GPA,但我可以在 GradePoint 中输入任何内容,它会输出一个值。我想要的是 GradePoint 仅在用户输入 0.0-4.0 之间的数字时才起作用。我正在考虑某种循环,例如 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()

这是 shell 打印输出(我知道成绩点在 GPA 中重复,这是针对一个类(class)的,我们应该使用一个骨架程序并更改一些东西):

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 循环,它在某种程度上起到了作用,因为它打印出了我想要的内容,但没有让它停止并等待正确的输入。我不太确定如何让它做到这一点。

这是来自 shell 的新打印内容:

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

最佳答案

您可以检查用户输入是否满足您的要求,如果不满足则抛出异常。这将使程序记录一条错误消息并在无效的用户输入时停止。

最基本的方法是使用断言语句:

def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
assert credits > 0 and credits < 4, "Please enter a number of Credit Hours between 0 and 4."

如果您希望应用程序不断提示用户直到输入有效输入,则至少需要一个 while 循环。

例如:

def main():
stu = Student(" ", 0.0, 0.0)
while True:
credits = int(input("Enter Credit Hours "))
if credits > 0 and credits < 4:
break
else:
print("Please enter a number of Credit Hours between 0 and 4")

while True:
gradePoint = float(input("Enter Grade Point"))
if gradePoint <= 4.0:
break
else:
print("Please enter a Grade Point that is less then 4.")

stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)

关于python - 如何使 float 在 python 3 中具有特定范围(或者我可以)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10149577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com