Search This Blog
Exploring the Wonders of Science, Technology, and Human Potential
Featured
- Get link
- X
- Other Apps
Flashcard in Python Project
Flashcard Class
```code snippet
class Flashcard:
def __init__(self,
question, answer):
self.question
= question
self.answer =
answer
```
- Flashcard Class: This class represents a single flashcard.
- `__init__` Method: This is the constructor method. It
initializes the flashcard with a question and an answer.
FlashcardDeck Class
```code snippet
class FlashcardDeck:
def __init__(self,
name):
self.name =
name
self.flashcards = []
```
- FlashcardDeck Class: This class represents a collection of
flashcards, known as a deck.
- `__init__` Method: This constructor initializes the deck
with a name and an empty list to hold flashcards.
Adding a Flashcard
```code snippet
def
add_flashcard(self, flashcard):
self.flashcards.append(flashcard)
```
- `add_flashcard` Method: This method adds a flashcard to
the deck's list of flashcards.
Viewing All Questions
```code snippet
def
view_all_questions(self):
for card in
self.flashcards:
print(f"Question: {card.question}")
```
- `view_all_questions` Method: This method prints out all
the questions from the flashcards in the deck.
Saving the Deck to a
File
```code snippet
def
save_to_file(self):
file_path =
f"{self.name}_deck.json"
with
open(file_path, 'w') as file:
data =
{"name": self.name, "flashcards": []}
for card
in self.flashcards:
data["flashcards"].append({"question":
card.question, "answer": card.answer})
json.dump(data, file)
```
- `save_to_file` Method: This method saves the deck to a
JSON file.
- File Path:
Constructs the file name using the deck's name.
- Opening File:
Opens the file in write mode.
- Data Structure:
Prepares a dictionary with the deck's name and flashcards.
- Loop Through
Flashcards: Adds each flashcard's question and answer to the data structure.
- Save Data: Writes
the data to the file in JSON format.
Loading a Deck from a
File
```code snippet
def
load_from_file(self):
file_path =
f"{self.name}_deck.json"
if
os.path.exists(file_path):
with
open(file_path, 'r') as file:
data =
json.load(file)
self.name = data["name"]
for
card_data in data["flashcards"]:
card = Flashcard(card_data["question"], card_data["answer"])
self.flashcards.append(card)
```
- `load_from_file` Method: This method loads a deck from a
JSON file.
- File Path:
Constructs the file name using the deck's name.
- Check File
Existence: Ensures the file exists before trying to load it.
- Open File: Opens
the file in read mode.
- Load Data: Reads
the JSON data from the file.
- Restore Flashcards:
Recreates flashcards from the loaded data and adds them to the deck.
Helper Functions
Create a Deck
```code snippet
def create_deck():
deck_name =
input("Enter the name for your new deck: ")
deck =
FlashcardDeck(deck_name)
return deck
```
- `create_deck` Function: Prompts the user to enter a name
for a new deck and creates it.
Add a Flashcard to a
Deck
```code snippet
def add_flashcard_to_deck(deck):
question =
input("Enter the question: ")
answer =
input("Enter the answer: ")
flashcard =
Flashcard(question, answer)
deck.add_flashcard(flashcard)
print("Flashcard added to the deck.")
```
- `add_flashcard_to_deck` Function: Prompts the user to
enter a question and answer, creates a flashcard, and adds it to the deck.
Study the Deck
```code snippet
def study_deck(deck):
for card in deck.flashcards:
input(f"Question: {card.question}\nPress Enter to reveal the
answer...")
print(f"Answer: {card.answer}")
```
- `study_deck` Function: Allows the user to study the deck
by showing each question and revealing the answer after pressing Enter.
Main Function
```code snippet
def main():
print("Welcome to the Flashcard App!")
deck = None
while True:
print("\nMenu:")
print("1.
Create a new deck")
print("2.
Load an existing deck")
print("3.
Add a flashcard to the current deck")
print("4.
View all questions in the current deck")
print("5.
Study the current deck")
print("6.
Save current deck to file")
print("7.
Quit")
choice =
input("Enter your choice (1-7): ")
if choice ==
'1':
deck =
create_deck()
elif choice ==
'2':
deck_name
= input("Enter the name of the deck to load: ")
deck =
FlashcardDeck(deck_name)
deck.load_from_file()
elif choice ==
'3':
if deck is
not None:
add_flashcard_to_deck(deck)
else:
print("Create or load a deck first.")
elif choice ==
'4':
if deck is not None:
deck.view_all_questions()
else:
print("Create or load a deck first.")
elif choice ==
'5':
if deck is
not None:
study_deck(deck)
else:
print("Create or load a deck
first.")
elif choice ==
'6':
if deck is
not None:
deck.save_to_file()
print("Deck saved to file.")
else:
print("Create or load a deck first.")
elif choice ==
'7':
break
else:
print("Invalid choice. Please enter a number between 1 and
7.")
if __name__ == "__main__":
main()
```
- `main` Function: This is the main program loop.
- Welcome Message:
Greets the user.
- Menu Loop:
Repeatedly shows a menu until the user decides to quit.
- Menu Options:
- Create a New
Deck: Calls `create_deck` to create a new deck.
- Load an Existing
Deck: Prompts for the deck name and loads it.
- Add Flashcard:
Adds a flashcard to the current deck (if it exists).
- View All
Questions: Displays all questions in the current deck (if it exists).
- Study Deck:
Allows the user to study the current deck (if it exists).
- Save Deck: Saves
the current deck to a file (if it exists).
- Quit: Exits the
program.
Final Notes
- Entry Point: `if __name__ == "__main__": main()`
ensures the `main` function runs only if this script is executed directly, not
if it's imported as a module.
- Get link
- X
- Other Apps
Popular Posts
What If India Loses this mindset of Reusing Things?
- Get link
- X
- Other Apps
Polar Bear is Suffering to Find Land Here is Why?
- Get link
- X
- Other Apps
Smarter move through technology revolution
- Get link
- X
- Other Apps
The Role of UX Design in Evolving Technology
- Get link
- X
- Other Apps
Comments
Post a Comment