首页 > 解决方案 > 如何获得连续相同的输入来中断循环?

问题描述

我正在尝试制作一个学生学分计算器。它必须显示文本: You did have too many study breaks当用户连续输入两次 0 时。代码也应该到此为止。我什至不知道要开始解决这个问题,但我已经准备好了其余的代码。

def main():

    months=int(input("Enter the number of months: "))
    total=0

    for i in range(months):
        points=float(input("Enter the number of credits in month {}: ".format(i+1)))
        total += points

    average=total/months
    if average >= 5:
        print(f"You are a full time student and your monthly credit point average is {average:.1f}")
    elif average < 5:
        print(f"Your monthly credit point average {average:.1f} does not classify you as a full time student.")



if __name__ == "__main__":
    main() 

因此,为了澄清,如果用户连续两次输入 0 点,则循环应该中断并显示文本。先感谢您。

标签: pythonfor-loopbreak

解决方案


只需跟踪先前的输入:

prev = -1
for i in range(months):
    points=float(input("Enter the number of credits in month {}: ".format(i+1)))
    if not (prev or points):
        break
    total += points
    prev = points

推荐阅读