如何实现用户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.txtfile 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-DDstring 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.txtfile. - 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
相关产品推荐
相关产品推荐

