You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python俯卧撑计数日志程序添加总次数统计功能?

给俯卧撑计数器添加总次数统计功能

你可以通过新增统计函数、更新菜单选项的方式实现需求,以下是修改后的完整代码:

import datetime

def log_pushups():
    try:
        reps = int(input("Enter the number of push-ups completed: "))
        if reps < 0:
            print("Please enter a non-negative number.")
            return

        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open("pushup_log.txt", "a") as f:
            f.write(f"{timestamp},{reps}\n")
        print(f"Logged {reps} push-ups at {timestamp}")
    except ValueError:
        print("Invalid input. Please enter a number.")

def view_log():
    try:
        with open("pushup_log.txt", "r") as f:
            print("\n--- Push-up Log ---")
            for line in f:
                print(line.strip())
            print("-------------------\n")
    except FileNotFoundError:
        print("No push-up log found yet.")

def calculate_total_reps():
    total = 0
    try:
        with open("pushup_log.txt", "r") as f:
            for line in f:
                # 按逗号分割日志行,提取次数部分
                parts = line.strip().split(",")
                if len(parts) == 2:
                    try:
                        total += int(parts[1])
                    except ValueError:
                        # 跳过格式错误的无效日志行
                        continue
        print(f"\nTotal push-ups completed: {total}\n")
    except FileNotFoundError:
        print("No push-up log found yet.")

while True:
    print("1. Log Push-ups")
    print("2. View Log")
    print("3. Calculate Total Push-ups")
    print("4. Exit")
    choice = input("Enter your choice: ")

    if choice == '1':
        log_pushups()
    elif choice == '2':
        view_log()
    elif choice == '3':
        calculate_total_reps()
    elif choice == '4':
        break
    else:
        print("Invalid choice. Please try again.")

关键修改说明

  • 新增calculate_total_reps()函数:读取日志文件并逐行解析俯卧撑次数,累加得到总和;同时处理日志不存在、格式错误的情况,避免程序崩溃。
  • 调整菜单选项:将原退出选项后移为第4项,新增第3项用于触发总次数统计,对应调用新增函数。

内容的提问来源于stack exchange,提问作者Jaimz Jonah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 01:40:18