我如何让程序在我的习惯跟踪器上跟踪完成的天数?

2024-05-16 14:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

I want to create a feature where the program will track the number of days the user has completed their habit. I attempted to do it below, but it only printed the integer 1, instead of adding up the days properly.

import click

names_file = open("names.txt", "r+")
habits_file = open("habits.txt", "r+")
habits_time = open("time.txt", "r+")
days_completed = + 1


# Welcome Message
print("Welcome to Habit Tracker by Synclare")

# User Info
if click.confirm('Are you a new user?', True):
   user_name = input("Welcome. What's your name? ")
   names_file.write(user_name)

   habit = input("\nEnter a habit: ")
   habits_file.write(habit)

   time = input("For how long do you want to do this habit?")
   habits_time.write(time)

   print("Habit created.")

   else:
           print("\nWelcome back, " + names_file.readline() + ".")
           if click.confirm('\nWould you like to view your current habits?', True):
           read_habit = habits_file.read()
           read_time = habits_time.read()
           print(read_habit + ": " + habits_time.read())

              if click.confirm("\nHave you completed today's habit?", True):
                  print("You have completed " + str(days_completed) + "/" + read_time)

Tags: thetoyoureadtimenamesdaysdo
3条回答

为了说明该概念(无错误检查,无功能):

if __name__ == '__main__':
    habits = {
        'Habit1': {'days': 1},
        'Habit2': {'days': 5}
        }

    print('You have following habits:')
    for index, habit in enumerate(habits, 1):
        print(f'{index}. {habit} - {habits[habit]["days"]} day(s)')

    i = int(input(f'Select habit to increment (1 - {len(habits)}): '))
    habit_from_input = list(habits.keys())[i-1]
    habits[habit_from_input]['days'] += 1

    print('You have following habits:')
    for index, habit in enumerate(habits, 1):
        print(f'{index}. {habit} - {habits[habit]["days"]} day(s)')

除了不存储days_completed之外,您还使用了:

days_completed = +1

不更新变量(即不向days_completed添加1)。使用:

days_completed += 1

或:

days_completed = days_completed + 1

目前,此语句仅将days_completed设置为+1(即1

我看不到您从文件中读取已完成天数的位置。我建议为习惯创建某种数据结构——至少是字典。此外,不清楚你所说的时间-重复的天数或总时间(以分钟为单位)是什么意思。 比如:

total_time = 6

habbits = {
    'habbit1': {'time': total_time},
    'habbit2': {'time': total_time}
    }

for h in habbits:
    print(f'For {h} you have spent {habbits[h]["time"]}')

相关问题 更多 >