• Предмет: Информатика
  • Автор: maksumka1356
  • Вопрос задан 3 месяца назад

Записник: Розробіть додаток, який дозволяє користувачеві вводити, зберігати та редагувати нотатки.

Написати кодом в пайтоне

Ответы

Ответ дал: deniss836
0

Объяснение:

Звісно, ось приклад простого консольного додатку для створення, збереження та редагування нотаток у Python:

```python

import os

class Note:

def __init__(self, title, content):

self.title = title

self.content = content

class NotesApp:

def __init__(self):

self.notes = []

def create_note(self, title, content):

note = Note(title, content)

self.notes.append(note)

print("Нотатку додано!")

def list_notes(self):

if not self.notes:

print("Немає жодних нотаток.")

else:

print("Список нотаток:")

for idx, note in enumerate(self.notes):

print(f"{idx + 1}. {note.title}")

def view_note(self, note_idx):

try:

note = self.notes[note_idx]

print(f"Заголовок: {note.title}")

print("Зміст:")

print(note.content)

except IndexError:

print("Нотатку з таким індексом не існує.")

def edit_note(self, note_idx, new_content):

try:

note = self.notes[note_idx]

note.content = new_content

print("Нотаток змінено!")

except IndexError:

print("Нотатку з таким індексом не існує.")

def save_notes(self, filename):

with open(filename, "w") as f:

for note in self.notes:

f.write(f"Заголовок: {note.title}\n")

f.write(note.content + "\n")

f.write("-" * 20 + "\n")

def load_notes(self, filename):

if os.path.exists(filename):

with open(filename, "r") as f:

lines = f.readlines()

title = ""

content = ""

for line in lines:

if line.startswith("Заголовок:"):

title = line.strip()[len("Заголовок: "):]

elif line.strip() == "-" * 20:

self.create_note(title, content)

title = ""

content = ""

else:

content += line

print("Нотатки завантажено!")

if __name__ == "__main__":

app = NotesApp()

save_file = "notes.txt"

app.load_notes(save_file)

while True:

print("\n1. Створити нотатку")

print("2. Переглянути список нотаток")

print("3. Переглянути нотатку")

print("4. Редагувати нотатку")

print("5. Зберегти нотатки")

print("6. Вийти")

choice = input("Виберіть опцію: ")

if choice == "1":

title = input("Введіть заголовок нотатки: ")

content = input("Введіть зміст нотатки: ")

app.create_note(title, content)

elif choice == "2":

app.list_notes()

elif choice == "3":

note_idx = int(input("Введіть індекс нотатки: ")) - 1

app.view_note(note_idx)

elif choice == "4":

note_idx = int(input("Введіть індекс нотатки для редагування: ")) - 1

new_content = input("Введіть новий зміст нотатки: ")

app.edit_note(note_idx, new_content)

elif choice == "5":

app.save_notes(save_file)

elif choice == "6":

break

else:

print("Неправильний вибір. Спробуйте знову.")

```

Цей код створює консольний додаток для створення, збереження та редагування нотаток. Нотатки зберігаються у файлі "notes.txt". Ви можете вдосконалити цей код, додати графічний інтерфейс або інші функціональні можливості, в залежності від вашого бажання.

Ответ дал: gguketosl
1

import os

class Note:

   def __init__(self, title, content):

       self.title = title

       self.content = content

class NoteApp:

   def __init__(self):

       self.notes = []

   

   def add_note(self):

       title = input("Введите заголовок заметки: ")

       content = input("Введите текст заметки: ")

       note = Note(title, content)

       self.notes.append(note)

       self.save_notes()

   

   def delete_note(self):

       title = input("Введите заголовок заметки: ")

       note_to_delete = None

       for note in self.notes:

           if note.title == title:

               note_to_delete = note

               break

       if note_to_delete:

           self.notes.remove(note_to_delete)

           self.save_notes()

           print("Заметка успешно удалена.")

       else:

           print("Заметка с таким заголовком не найдена.")

   

   def edit_note(self):

       title = input("Введите заголовок заметки: ")

       note_to_edit = None

       for note in self.notes:

           if note.title == title:

               note_to_edit = note

               break

       if note_to_edit:

           new_title = input("Введите новый заголовок заметки (оставьте пустым, чтобы сохранить текущий): ")

           if new_title:

               note_to_edit.title = new_title

           new_content = input("Введите новый текст заметки (оставьте пустым, чтобы сохранить текущий): ")

           if new_content:

               note_to_edit.content = new_content

           self.save_notes()

           print("Заметка успешно отредактирована.")

       else:

           print("Заметка с таким заголовком не найдена.")

   

   def view_notes(self):

       for note in self.notes:

           print(note.title)

           print(note.content)

   

   def load_notes(self):

       if os.path.exists("notes.txt"):

           with open("notes.txt", "r") as f:

               for line in f:

                   if line.strip():

                       title, content = line.strip().split("|")

                       note = Note(title, content)

                       self.notes.append(note)

   

   def save_notes(self):

       with open("notes.txt", "w") as f:

           for note in self.notes:

               f.write(f"{note.title}|{note.content}\n")

app = NoteApp()

app.load_notes()

while True:

   print("1. Добавить заметку")

   print("2. Удалить заметку")

   print("3. Редактировать заметку")

   print("4. Просмотреть заметки")

   print("5. Выход")

   choice = input("Выберите действие: ")

   if choice == "1":

       app.add_note()

   elif choice == "2":

       app.delete_note()

   elif choice == "3":

       app.edit_note()

   elif choice == "4":

       app.view_notes()

   elif choice == "5":

       break

   else:

       print("Неверный выбор.")

Вас заинтересует