Day 062 - Project 62 : My Private Diary

If you have any questions, comments or issues with this project please post them here!

2 Likes

theres 2 issues in this code 1st one is I dk how to make my if statement equal to the data stored in my database so I can’t get the part to work where if the security question is equal to the one in the database it’ll open else exit !
2nd one something having an issue with the viewing of the diaries I can add data but viewing either shows blank lists or nothing at all :smiling_face_with_tear: DB is confusing

from replit import db
import datetime,os,time
print("Diary creator")
print()
name=input("Enter your name\n~ ")
logpassword=input ("Select you'r password\n~ ")
securityque=input("please enter you'r Birthdate to continue further(date/month/year)\n~  ")
key=f"name{logpassword}"
db[key] = securityque
os.system("clear")
print("..........")
time.sleep(1)
print("Processing")
time.sleep(0.5)
os.system("clear")
print ("\033[31m ALERT ALERT **\033[30mPrivate Diary\033[31m** ALERT ALERT\033[0m")
password=input ("Password \n~ ")
time.sleep(0.2)
os.system("clear")
if password!=logpassword:
  time.sleep(0.2)
  print("\033[31mALERT Wrong Password ALERT")
  print("\033[31mALERT Wrong Password ALERT")
  print("\033[31mALERT Wrong Password ALERT\033[0m")
  os.system("clear")
  resetpass=input("would you like to reset you'r password\n~  ")
  if resetpass== "yes":
    securityque=input("please enter you'r Birthdate to continue further(date/month/year)\n~  ")
    os.system("clear")
    #if securityque answer equal to the one in our database then we continue otherwise we exit
    if securityque!=0:
      print()
      print("welcome", name)
    else:
      os.syetm("clear")
      print("\033[31mALERT ALERT ALERT ALERT\033[0m")
      print()
      print("system failure you dont belong here")
      os.system("clear")
      exit()
  else:
    exit()  
def addDiary():
  os.system("clear")
  time.sleep(0.2)
  print("welcome to your diary",name)
  print("what'd you like to add")
  add=input("~ ")
  print()
  timestamp=datetime.datetime.now()
  print(f"This is your work today{timestamp}")
  db[timestamp] =add
  time.sleep(1)
  os.system("clear")
def viewDiary():
  matches = db.prefix("timestamp")
  for i in matches:
    print(matches)
    time.sleep(1)
    os.system("clear")
print("Welcome",name)
print()
while True:
  print("Lets add what we did to shall we")
  print()
  menu=input("1:Add\n\t 2:View\n ~")
  if menu=="1":
    addDiary()
  elif menu== "2":
    viewDiary()

For the second issue:
I have updated the addDiary function so it looks like this.

def addDiary():
  os.system("clear")
  time.sleep(0.2)
  print("welcome to your diary",name)
  print("what'd you like to add")
  add=input("~ ")
  print()
  timestamp=datetime.datetime.now()
  print(f"This is your work today{timestamp}")
  db["timestamp"+str(timestamp)] = add #changed this line
  time.sleep(1)
  os.system("clear")

The reason that it did not work is that you are using matches = db.prefix("timestamp") which will get all of the keys that start with “timestamp” but when you make the key you do not add “timestamp” before the time.

1 Like

For the first thing:

from replit import db
import datetime,os,time
print("Diary creator")
print()
name=input("Enter your name\n~ ")
logpassword=input ("Select you'r password\n~ ")
securityque=input("please enter you'r Birthdate to continue further(date/month/year)\n~  ")
db["password"] = logpassword #set the password
db["securityque"] = securityque #set the securityque
os.system("clear")
print("..........")
time.sleep(1)
print("Processing")
time.sleep(0.5)
os.system("clear")
print ("\033[31m ALERT ALERT **\033[30mPrivate Diary\033[31m** ALERT ALERT\033[0m")
password=input ("Password \n~ ")
time.sleep(0.2)
os.system("clear")
if db["password"] !=password: #get and test the password
  time.sleep(0.2)
  print("\033[31mALERT Wrong Password ALERT")
  print("\033[31mALERT Wrong Password ALERT")
  print("\033[31mALERT Wrong Password ALERT\033[0m")
  os.system("clear")
  resetpass=input("would you like to reset you'r password\n~  ")
  if resetpass== "yes":
    securityque=input("please enter you'r Birthdate to continue further(date/month/year)\n~  ")
    os.system("clear")
    #if securityque answer equal to the one in our database then we continue otherwise we exit
    if securityque == db["securityque"]: #get and test the securityque
      print()
      print("welcome", name)
    else:
      os.syetm("clear")
      print("\033[31mALERT ALERT ALERT ALERT\033[0m")
      print()
      print("system failure you dont belong here")
      os.system("clear")
      exit()
  else:
    exit()  

I have made it so the password get set to a key called “password” and the same for securityque.

1 Like

@GoodVessel92551,
wow thanks a lot! gotta practice this one db is confusing me a lot

1 Like

ahha now I got it timestamp was just time so it can’t be called on the match function so I had to include a string line called timestamp! noice thanks :+1:

1 Like

understood this part as well if I’m right so we create the name password as in db name then put the value on logpassword like storing the value on a variable with extra steps lol :man_facepalming:
anyways thank you for the help ! appreciated @GoodVessel92551 !

1 Like
import os,time,datetime
from replit import db

def Add():
  today = datetime.datetime.now()
  Add = input("Entry: ")
  db[today] = Add
  print("Entry is been added")

def View():
  os.system("clear")
  data_base = db.keys()
  data_base = sorted(data_base,reverse=True)
  counter = 0 
  for keys in data_base:
    print(f"{keys}: {db[keys]}")
    print()
    next = input("Next(y/n): ")
    if next[0].lower() == "y":
      os.system("clear")
      counter += 1
      if counter == len(data_base):
        print("NO Other Enrty Presents")
        time.sleep(1)
      continue
    if next[0].lower() == "n":
      os.system("clear")
      break

def exactDate():
  date = input("Enter the date: ")
  

  time_stamp = db.prefix(date)
  for i in time_stamp:
    print(f"{i}: {db[i]}")
    
heading = "Diary Entrie"
print(f"{heading:^50}")
print()

password = input("Enter the password: ")
if password != "p23anther291":
  exit()
  
else:
  os.system("clear")
  while True:
    print("Private Diary")
    print()
    print("""1.Add
2.View
3.Entry for exact date""")
    choice = int(input("> "))
    print()
    if choice == 1:
      Add()
    if choice == 2:
      View()
    if choice == 3:
      exactDate()
    time.sleep(1)
    os.system("clear")

This can Help you with adding a feature which allows the user to view an entry from an exact date.

1 Like

Hi Y’all - This Time I was a bit struggling. I have 2 Problems I got stuck with and David’s not explaining it in his solution video. :pensive:

  1. When going through the diary one by one, I am using a recursive function for that, which works fine. But I want it to print “End of Diary” when it reaches the end. How can I do that??

  2. I am trying to build the search function (by date). I tried the inbuilt function “db.prefix( )” but it turns my diary into a tuple and I can’t access the entries. So I am trying to leap through the dictionary by telling it which part of the key to match (first 10 characters). That is not working however, and I cannot figure out why.

I appreciate your help so much ! :pray:

from replit import db
import datetime, os, time


def display(y, x):
  # when no more entries in diary
  #print("End of Diary")
  for entry in diary[y:x]:
    print(f"{entry}:\n{db[entry]}\n\n")
    input("Press Enter to view next one\n")
    display(y + 1, x + 1)


def search(day, month):
  prefix = f"2023-{month:02d}-{day:02d}"
  for entry in diary:
    if diary[0:9] == prefix:
      print(f"{entry}: \n{db[entry]}\n\n")
    else:
      print(f"no entry found on {prefix}")



password = "hundred"
user = input("Enter password: ")
if password != user:
  print('Sorry, no.')
  exit()
else:
  pass

while True:
  diary = sorted(db.keys(), reverse=True)
  os.system("clear")
  print("   DIARY")
  print("=============\n")
  select = input("Add, View or Search?\n")
  if select[0] == "a":
    entry = input("Type your entry here:\n")
    timestamp = datetime.datetime.now()
    db[timestamp] = entry
  elif select[0] == "v":
    display(0, 1)
  elif select[0] == "s":
    day = int(input("Enter Day: "))
    month = int(input("Enter Month: "))
    search(day, month)
  input("\n\npress enter to return")

2 Likes

I truly cannot understand some part of your code. So I might just be giving you a wrong answer.
Why do you do a loop and recursion? to me it seems not actually needed

def display(diary):
  for entry in diary:
    print(f"{entry}:\n{db[entry]}\n\n")
    input("Press Enter to view next one\n")

  print("End of Diary")

Also try to pass diary as parameter since, even if working, you are now declaring a function using diary before it is even declared, which can lead to strange things.

2 Likes

oh boy, i was kinda re-doing with the recursion what the for loop is doing anyway :joy::joy::see_no_evil:
thanks for pointing that out! i tend to overcomplicate my code…

Also thanks for the parameter hint. I’m starting to get the hang of these subroutines and how to use them properly!

Any idea for my 2) question?

1 Like

If I understand correctly, you are using dates as key and diary as a list of all keys.
Now the best is to use this information to compare dates and not strings.
This alone is an interesting new thing you should do.

So first try to figure out how to convert dates to and from string, and compare dates.
Then try linear search (start from one end of diary and go on …).
Then you can search or ask here how to do something faster than linear search,

Now the true programming fun will begin :slight_smile:

I could show you code, but trying like this will in the end help you more

2 Likes

Not sure if you’ll be happy with my solution but I made it! :partying_face:
I found the operator library useful for this…

I know I am not really converting the timestamp to a string, but this works for now… You gotta be easy on me! :sweat_smile:

Check it out:

from replit import db
import datetime, os, time


def display(diary):
  for entry in diary:
    print(f"{entry}:\n{db[entry]}\n\n")
    input("Press Enter to view next one\n")
  print("\nEnd of Diary")


def search(day, month):
  prefix = f"2023-{month:02d}-{day:02d}"
  result = {}
  import operator
  for i, j in db.items():
    if (operator.contains(i, prefix)):
      result[i] = j
  for i, j in result.items():
    print(f"{i}:\n{j}\n\n")


password = "hundred"
user = input("Enter password: ")
if password != user:
  print('Sorry, no.')
  exit()
else:
  pass

while True:
  diary = sorted(db.keys(), reverse=True)
  os.system("clear")
  print("   DIARY")
  print("=============\n")
  select = input("Add, View or Search?\n")
  if select[0] == "a":
    entry = input("Type your entry here:\n")
    timestamp = datetime.datetime.now()
    db[timestamp] = entry
  elif select[0] == "v":
    display(diary)
  elif select[0] == "s":
    day = int(input("Enter Day: "))
    month = int(input("Enter Month: "))
    search(day, month)
  input("\n\npress enter to return")

1 Like

Making it work is always the first great step :slight_smile:

2 Likes

i know you already fixed your 2nd issue, but i looked at it again because i still can’t get used to dictionaries (lists are more my thing) and because your idea looked like it should work. only 2 small changes necessary in the if statement, 1) you were 1 character short when comparing the date, 2) compared it to the first 9 entries of the dictionary, not to the first 9 characters of the entry key

image

importing inside of functions are bad practice. Just import operator at the top of your file. =)

1 Like

Hi @QwertyQwerty88 - Yes I totally agree!
But I was importing this function from my own library, so needed to make sure the required library comes with it.
How would you deal with that in such case?

Hey, all. Sharing my unsexy method for comparing two dates for the ‘extra credit’ David mentioned. The issue I had was saving the timestamp to the dictionary converted it to a string. Casting the same entry as a date again using the datetime.strptime()saved the day. This took me WAY too long to figure out…

def viewByDate():
  month = int(input("Enter month: "))
  day = int(input("Enter day: "))
  year = int(input("Enter year: "))
  searchDate = datetime.date(year, month, day)
  print(f"Showing entries on {searchDate}...\n")
  found = False
  for i in db.keys():
    date_object = datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S.%f').date()
    if searchDate == date_object:
      print(f"{i}\nJournal Entry:\t{db[i]['entry']}\nWorkout:\t{db[i]['workout']}\nDiet:\t{db[i]['diet']}\n")
      found = True
  if found == False:
    print("No entries found.")
  time.sleep(2)
1 Like

For future reference, one way to make life easier is to use epoch time that turns any date into a number that can be easily converted to/from strings.
This is a little example … maybe this wil help some people :slight_smile:

import datetime

month = int(input("Enter month: "))
day = int(input("Enter day: "))
year = int(input("Enter year: "))
db_key_epochtime = int(datetime.datetime(year, month, day).timestamp())

print(db_key_epochtime)

This is also useful as a type of timestamp often used in real life programming.

2 Likes

I started the “view entry” subroutine with some basic code

keys=db.keys()  
index = 0
date = keys[index]
entry = db[date]
print(f”{date}: {entry})

However, that gave me an error of something like “typeerror object is not subscriptable.”

I forgot to add some entries into the database before drawing from the database, so I would like to know, would my code have worked if there was something in the database?

I didn’t realize my mistake yet, so I continued with something simpler:

keys=db.keys()
date = keys[0]
print(date)

my thinking was that perhaps I couldn’t index a list with a variable.

finally, I tried

keys=db.keys()
print(keys)

and this didn’t return anything except for

set()

so I realized that I received a new database for every new day of coding, and my tweets weren’t accessible from the new repl.

Is the original error I encountered the error that David mentioned when he said to use a try except block? It seems that my first line created an empty list, so I would need to come up with some try except block of code for the case where the user attempts to view log entries before they every create one.