0% found this document useful (0 votes)
2 views22 pages

Python 8a Notes - updated 2 (1)

The document outlines the design and functionality of a Credit Card Payment Tracker program implemented in Python, which allows users to manage their credit card minimum payments through a menu-driven interface. Key features include viewing, adding, updating, and deleting payment records, with input validation for credit card names. The program ensures data persistence by saving records to a text file and utilizes f-strings for formatting output.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Python 8a Notes - updated 2 (1)

The document outlines the design and functionality of a Credit Card Payment Tracker program implemented in Python, which allows users to manage their credit card minimum payments through a menu-driven interface. Key features include viewing, adding, updating, and deleting payment records, with input validation for credit card names. The program ensures data persistence by saving records to a text file and utilizes f-strings for formatting output.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

P.

1 of 22

Contents

Example of combining File and Dictionary .................................................................... 2


Credit Card Payment Tracker.................................................................................. 2
Choice 1 – Display all the records in the system ............................................ 5
Choice 2 - Input minimum payment .............................................................. 6
Extra requirement for entering record – Maximum of 7 characters ..... 6
Extra requirement for entering record – Prevent from empty input..... 7
Choice 3 – Edit record of minimum payment ................................................ 8
Extra requirement for entering record – Credit card name can’t be
found ...................................................................................................... 8
Choice 4 – Delete record of minimum payment ............................................ 9
Extra requirements for deleting minimum payment ........................... 10
Choice 5 – Exit the system ........................................................................... 11
Using f-strings in Python ...................................................................................... 12
What are f-strings?....................................................................................... 12
Basic Syntax .......................................................................................... 12
Embedding Expressions ....................................................................... 12
Using Functions and Method Calls ...................................................... 13
Specifying Formats ............................................................................... 13
Common Format Specifiers:......................................................... 13
Multi-line f-strings................................................................................ 14
Escaping Braces .................................................................................... 14
Elaboration of creditcard.py ................................................................................ 15
P. 2 of 22

Example of combining File and


Dictionary
The Credit Card Payment Tracker is designed for users who want a lightweight and
practical tool to manage their credit card minimum payments. It is especially useful
for individuals prioritizing financial discipline and record-keeping without relying on
complex software. The program’s simplicity and persistence make it a valuable tool
for everyday use.

Credit Card Payment Tracker


The Credit Card Payment Tracker is a simple yet effective menu-driven program
designed to help users manage their credit card minimum payments efficiently. With
this program, users can view, add, update, or delete payment records, ensuring their
financial obligations are organized and up to date. The system is implemented using
Python and stores data persistently in a text file (payment.txt), making it easy to track
changes over time.

The payment.txt should be a text file storing data with the following format:
P. 3 of 22

Features of the Credit Card Payment Tracker:

1. View Payments:
➢ Displays all existing credit card payment records in a clear and
organized format.
➢ Provides an overview of the current financial commitments.

2. Add a New Payment:


➢ Allows users to add a new credit card and its associated minimum
payment.
➢ Ensures input validation by restricting credit card names to a
maximum of 7 characters and preventing empty inputs.

3. Update an Existing Payment:


➢ Provides an option to modify the minimum payment of an existing
credit card.
➢ Ensures that only valid credit card names can be updated.

4. Delete a Payment:
➢ Enables users to delete a specific credit card payment record.
➢ Includes a confirmation step to prevent accidental deletion, with
proper warnings for invalid inputs.

5. Save and Exit:


➢ Saves all changes to the payment.txt file, ensuring data persistence.
➢ Exits the program gracefully after saving.

How It Works:

➢ The program dynamically loads data from payment.txt at the start and saves
changes to the file upon exit.
➢ A menu-based interface allows users to interact with the system through
simple numeric choices.
➢ Input validation ensures that only valid data is accepted, improving reliability
and user experience.
➢ The system clears the screen between actions for a clean and professional
look.
P. 4 of 22

The tracker will start by providing a menu for user to opt for handling minimum
payment.
P. 5 of 22

Choice 1 – Display all the records in the system


If option 1 is selected, all the credit card names and minimum payments will be
displayed to user:
P. 6 of 22

Choice 2 - Input minimum payment


If user chooses option 2, he / she will be asked to input the information of a credit
card name and minimum payment. That is:

Extra requirement for entering record – Maximum of 7 characters

Notice that we have to set the system only allows user to input credit card name in a
maximum of 7 characters.
P. 7 of 22

Extra requirement for entering record – Prevent from empty input

Notice that the system should prevent using from any empty input of credit card
name.
P. 8 of 22

Choice 3 – Edit record of minimum payment


If user wants to edit current record of minimum payment, we can first show out all
the records for user’s reference. Then let user input credit card name and updated
amount.

Extra requirement for entering record – Credit card name can’t be found

Notice that the system should notify user in case the credit card name can’t be
found.
P. 9 of 22

Choice 4 – Delete record of minimum payment


The system allows user to delete record of a credit card and minimum payment. See
the following screen for reference:
P. 10 of 22

Extra requirements for deleting minimum payment

1. If the credit card name provided by user can’t be found in the system, the
user should be noticed by this issue:

2. If user input something other than y/n or Y/N, they will be warned as shown
below:
P. 11 of 22

Choice 5 – Exit the system


Option 5 would be the most simple stuff as it only helps to write data in text file and
thereafter quit the system. That is:
P. 12 of 22

Using f-strings in Python


What are f-strings?
➢ f-strings (formatted string literals) are a way to embed expressions inside string
literals, using curly braces {}.
➢ Introduced in Python 3.6, they provide a concise and readable way to format
strings.
➢ More readable and concise compared to older formatting methods like % or
str.format().

Basic Syntax

To create an f-string, prefix the string with the letter f or F:

Embedding Expressions

You can embed any valid Python expression inside {}:


P. 13 of 22

Using Functions and Method Calls

You can call functions or methods directly inside {}:

Specifying Formats

f-strings support format specifications, just like the str.format() method:

Common Format Specifiers:


Format Description Example
.2f Fixed-point, 2 decimal places f"{3.14159:.2f}" → 3.14
, Adds a comma as a thousand separator f"{1234567:,}" → 1,234,567
% Percentage f"{0.25:.0%}" → 25%
P. 14 of 22

Multi-line f-strings

You can use f-strings across multiple lines by enclosing them in triple quotes:

Escaping Braces

To include literal curly braces {} in an f-string, double them:


P. 15 of 22

Elaboration of creditcard.py
As we have learned the way to use f-strings, let’s walk through the creditcard.py
Python program. It is the one focusing on code structure, syntax, and functionality.

1. Importing Modules
import os

➢ Imports Python's os module, which provides functions to interact with the


operating system.
➢ Useful for tasks like file handling, directory management, and executing
system commands (e.g., clearing the screen).

2. Variables for File Management


CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
FILE_NAME = os.path.join(CURRENT_PATH, "payment.txt")

➢ os.path.abspath(__file__):
✓ Gets the full absolute path of the current script.

➢ os.path.dirname():
✓ Extracts the directory path of the file from the absolute path.

➢ os.path.join(CURRENT_PATH, "payment.txt"):
✓ Combines the directory path (CURRENT_PATH) with the filename
payment.txt to create a full file path.

3. Clear Screen Function


def clear_screen():
os.system('cls')

➢ Function definition:
✓ def clear_screen():: Defines a function named clear_screen
with no parameters.
➢ os.system('cls'):
✓ Executes the system command cls (clear screen) on Windows.
P. 16 of 22

4. Load Data Function


Syntax Breakdown:
def load_data():
if not os.path.exists(FILE_NAME):
return {}
with open(FILE_NAME, "r") as file:
lines = file.readlines()
data = {}
for line in lines:
card, amount = line.strip().split(":")
data[card] = amount
return data

A. Function Definition:
➢ def load_data()::
Begins the definition of the load_data function, which loads credit
card payment data from a file.

B. Check File Existence:


➢ if not os.path.exists(FILE_NAME)::
Checks if the file payment.txt exists using os.path.exists().
➢ If the file doesn't exist, it returns an empty dictionary (return {}).

C. Open File:
➢ with open(FILE_NAME, "r") as file::
✓ Opens the file in read mode ("r"). The with statement
ensures the file is properly closed after reading.
➢ file.readlines():
✓ Reads all lines of the file into a list called lines.
P. 17 of 22

D. Process File Data:


➢ for line in lines::
Iterates through each line in the file.
➢ line.strip().split(":"):
✓ strip() removes leading/trailing whitespace or newline
characters.
✓ split(":") splits each line into two parts (card name and
amount) using the colon : as a delimiter.
➢ data[card] = amount:
Adds the card name and its amount to the dictionary data.

E. Return the Data:


➢ The function returns the data dictionary.

{'BOC': '1230', 'HSBC': '600', 'AE Card': '180', 'DBS': '310',

'ICBC': '100', 'HSB': '200'}

data dictionary

“AE
key “BOC” “HSBC” “DBS” “ICBC” “HSB”
Card”

value 1230 600 180 310 100 200


P. 18 of 22

5. Save Data Function


def save_data(data):
with open(FILE_NAME, "w") as file:
for card, amount in data.items():
file.write(f"{card}:{amount}\n")

A. Function Definition:
➢ def save_data(data)::
Defines a function to save the dictionary data into the file.

B. Open File in Write Mode:


➢ with open(FILE_NAME, "w") as file::
✓ Opens the file in write mode ("w"), which overwrites its
contents.

C. Write Dictionary Data to File:


➢ for card, amount in data.items()::
Loops through each key-value pair in the dictionary.

➢ file.write(f"{card}:{amount}\n"):
✓ Writes each key-value pair as card:amount on a separate line
in the file.

6. Display Menu Function


def display_menu():
print("\nCredit Card Payment Tracker")
print("1. View all payments")
print("2. Add a new payment")
print("3. Update an existing payment")
print("4. Delete a payment")
print("5. Save and exit")

A. Function Definition:
➢ def display_menu()::
Defines the function that displays the main menu options.

B. print Statements:
➢ Each print() displays a menu option for the user to choose from.
P. 19 of 22

7. View Payments
def view_payments(data):
clear_screen()
if not data:
print("No payments found.")
else:
print("\nCurrent Payments:")
for card, amount in data.items():
print(f"{card}: {amount}")
input("\nPress Enter to return to the menu...")

A. Clear Screen:
➢ clear_screen():
Clears the terminal before displaying payments.

B. Check for Empty Data:


➢ if not data::
Checks if the dictionary is empty.
➢ If empty, it prints No payments found.

C. Display Data:
➢ for card, amount in data.items()::
Loops through the dictionary and prints each card name and its
amount.

D. Wait for User Input:


➢ input("\nPress Enter to return to the menu..."):
Pauses the program until the user presses Enter.
P. 20 of 22

8. Input Validation for Card Names


def get_valid_card_name():
while True:
card = input("Enter the name of the credit card (max 7
characters): ").strip()
if not card:
print("Error: Credit card name cannot be empty.
Please try again.")
elif len(card) > 7:
print("Error: Credit card name must be 7 characters
or less. Please try again.")
else:
return card

A. Loop Until Valid Input:


➢ Uses a while True loop to keep asking for input until a valid card
name is entered.

B. Validation Checks:
➢ If the card name is empty (if not card), an error message is
displayed.
➢ If the card name exceeds 7 characters (len(card) > 7), another
error message is displayed.

C. Return Valid Input:


➢ When input passes validation, it is returned using return card.
P. 21 of 22

9. Menu Options (Add, Update, Delete Payments)

Add Payment:
➢ Prompts the user to enter a new card name and minimum payment.
➢ Checks if the card already exists and displays an error if it does.

Update Payment:
➢ Allows the user to modify the payment amount for an existing card.

Delete Payment:
➢ Prompts the user to confirm before removing a card from the dictionary.

10. Main Function


def main():
data = load_data()
while True:
clear_screen()
display_menu()
choice = input("Enter your choice (1-5): ")
if choice == "1":
view_payments(data)
elif choice == "2":
add_payment(data)
elif choice == "3":
update_payment(data)
elif choice == "4":
delete_payment(data)
elif choice == "5":
save_data(data)
print(f"Data saved already.")
print("\nThank you for using the Credit Card
Payment Tracker system!")
break
else:
print("Invalid choice. Please try again.")
input("\nPress Enter to return to the menu...")
P. 22 of 22

➢ Menu Loop:
✓ Uses while True to keep displaying the menu until the user chooses to
exit (choice == "5").

➢ User Input:
✓ Prompts the user to select an option with input().

➢ Option Handling:
✓ Each menu option is handled with an if-elif block.

➢ Exit and Save:


✓ When the user chooses 5, the data is saved, and the program ends
with break.

11. Program Execution


main()
➢ Calls the main() function to start the program.

You might also like