python - 如何获得连续相同的输入来中断循环?
问题描述
我正在尝试制作一个学生学分计算器。它必须显示文本: 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 点,则循环应该中断并显示文本。先感谢您。
解决方案
只需跟踪先前的输入:
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
推荐阅读
- python - 在这个 Singleton 装饰器实现中,何时调用 __init__ ,它究竟做了什么?
- tfs - 我可以从检测 TeamCity 中的 TFS 更改中排除某些子文件夹吗?
- python - 如何对目录进行原子更新?
- python - 如何使用 Python 在运行时网页中进行调试
- javascript - React + D3:如何访问对象的状态和道具?(在事件触发的函数内)a
- javascript - Slick Carousel 自动播放视频 slide1
- apache-spark - 使用 pyspark 批处理作业从 Kafka 读取最新记录
- kubernetes - 如何使用 UnexpectedAdmissionError 恢复 pod
- python-3.x - 如何显示数据框列中出现次数最多的行?
- python - 如果我使用在线 IDE,是否需要 SFTP?