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

如何实现用户input()每日仅可输入一次?基于现有代码的优化问询

Limit Daily Input to One Submission Using Date Tracking

Great question! The core idea here is to persistently track the last date the user submitted input so your program can check if today’s already had a submission before prompting again. Timestamp works, but comparing full dates is simpler for this use case. Let’s modify your code step by step:

Step 1: Add Dependencies & Helper Function

We’ll use datetime to handle date checks and os to manage a small storage file (so we don’t crash if the file doesn’t exist yet). Add these imports at the top:

import datetime
import os

Then create a helper function to verify if the user has already submitted today:

def has_submitted_today():
    # File to store the last submission date
    date_file = "last_submission.txt"
    if not os.path.exists(date_file):
        return False
    
    # Read the stored date from the file
    with open(date_file, "r") as f:
        last_date_str = f.read().strip()
    
    # Get today's date formatted as a string (YYYY-MM-DD)
    today = datetime.date.today().strftime("%Y-%m-%d")
    
    # Check if last submission was on today
    return last_date_str == today

Step 2: Update Input Logic & Submission Flow

Modify your existing functions to only ask for input if no submission exists for today:

def inputQ1(): 
    while True: 
        try: 
            Q1A = int(input("Rate your exercise today on scale 1-100: "))
            # Optional: Validate the rating is within 1-100
            if not 1 <= Q1A <= 100:
                print("Please enter a number between 1 and 100!")
                continue
        except ValueError: 
            print("Invalid value - please enter an integer.") 
            continue 
        else: 
            return Q1A 

# Initialize your answer list
ansQ1 = [] 

# Only prompt for input if no submission today
if not has_submitted_today():
    user_rating = inputQ1()
    ansQ1.append(user_rating)
    print(f"Thanks! Your rating {user_rating} has been saved.")
    
    # Save today's date to the storage file
    with open("last_submission.txt", "w") as f:
        f.write(datetime.date.today().strftime("%Y-%m-%d"))
else:
    print("You've already submitted your exercise rating today! Come back tomorrow.")

print(ansQ1)

How This Works

  • Persistent Storage: The last_submission.txt file retains the last submission date even after the program closes. This ensures the check works across sessions.
  • Simple Date Comparison: By converting dates to a YYYY-MM-DD string format, we avoid complex timestamp math and make the check straightforward.
  • Extra Validation: I added a check to ensure the user enters a valid 1-100 rating (matching your prompt) — feel free to remove this if you don’t need it.

Quick Notes

  • To test the logic again before tomorrow, just delete the last_submission.txt file.
  • For a more robust solution (e.g., tracking multiple users), you could use a small database like SQLite, but a text file is perfect for this simple use case.

内容的提问来源于stack exchange,提问作者0myjoe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 03:37:41