【发布时间】:2014-10-02 04:50:02
【问题描述】:
GPA 或平均绩点的计算方法是将学生在课程中获得的绩点相加,然后除以总学分。单个课程的成绩点是通过将该课程的学分乘以取决于所获得成绩的适当因子来计算的:
A receives 4 grade points
B receives 3 grade points
C receives 2 grade points
D receives 1 grade point
F receives 0 grade point
您的程序将有一个用于计算多个 GPA 的 while 循环和一个用于收集个人成绩的 while 循环(即嵌套的 while 循环)。
对于您的演示,将这两个课程组合的 GPA 计算到小数点后 2 位:
First Case: 5 units of A 4 units of B 3 units of C
Second Case: 6 units of A 6 units of B 4 units of C
这是我目前所拥有的......
todo = int(input("How many GPA's would you like to calculate? "))
while True: x in range (1, todo+1)
n = int(input("How many courses will you input? "))
totpoints = 0
totunits = 0
while True: range(1, n+1)
grade = input("Enter grade for course: " )
if grade == 'A':
grade = int(4)
if grade == 'B':
grade = int(3)
if grade == 'C':
grade = int(2)
if grade == 'D':
grade = int(1)
if grade == 'F':
grade = int(0)
units = int(input("How many units was the course? "))
totunits += units
points = grade*units
totpoints += points
GPA = totpoints / totunits
print("GPA is ", ("%.2f" % GPA))
print("total points = ", totpoints)
print("total units = ", totunits)
我的问题是如何正确地合并 while 函数?我的代码运行不正确。
提前致谢。
【问题讨论】:
-
您不需要
while循环,因为您使用的是for循环。这通常更惯用且更具可读性,但如果您的作业需要while循环,则必须重写它以使用它。 -
换句话说:您需要为
x设置一个起始值,然后使用while (some condition on x):,然后在循环内部以某种方式更新x。 -
所以我只是用while替换它吗? while 函数不需要 if else elif 吗?
-
不,
while循环不需要if/else。while语句内置了一个条件。您可以改为使用while True:,并在内部使用if (opposite of condition on x): break或类似的,有时您必须这样做,但通常这不是必需的. -
我做了,现在代码无法运行。你能告诉我怎么做吗?
标签: python while-loop