تتبع إنفاقك (أو عاداتك)
تعرف على كيفية تسجيل إدخال المنظمة في ملف.
دعونا بناء مشروع Python حقيقي: متتبع!
يمكنك استخدامه لتسجيل الإنفاق والعادات والتدريبات - أي شيء تريد الاحتفاظ بسجل له.
الخطوة 1: مسجل الإنفاق البسيط
while True:
item = input("Enter an item (or 'done' to finish): ")
if item == "done":
break
amount = input("How much did you spend on it? ")
with open("expenses.txt", "a") as file:
file.write(item + ": $" + amount + "\n") # Concatenate the strings before writing
print("All expenses saved!")We’re asking the user for what they spent on and how much, and saving it to a file
ملاحظة:
item،": $"،amount، و"\n"يتم دمجها في سلسلة واحدة باستخدام+المشغل.يتم بعد ذلك كتابة هذه السلسلة المتسلسلة الفردية إلى الملف باستخدام
file.write().
لقد قمت للتو بإنشاء مسجل نفقات مستمر!
الخطوة 2: قراءة وعرض النفقات
while True:
item = input("Enter an item (or 'done' to finish): ")
if item == "done":
break
amount = input("How much did you spend on it? ")
with open("expenses.txt", "a") as file:
file.write(item + ": $" + amount + "\n")
with open("expenses.txt", "r") as file:
print("Here are your expenses:")
print(file.read())
We’re reading back all past entries and showing them on screen
يعرض هذا جميع العناصر المسجلة لديك—حتى من الأسبوع الماضي!
تحسين مع الوظائف
قم بتقسيم الكود الخاص بك إلى وظائف من أجل الوضوح:
def log_expense():
while True:
item = input("Enter an item (or 'done' to finish): ")
if item == "done":
break
amount = input("How much did you spend on it? ")
with open("expenses.txt", "a") as file:
file.write(item + ": $" + amount + "\n")
print("All expenses saved!")
def view_expenses():
with open("expenses.txt", "r") as file:
print("Here are your expenses:")
print(file.read())
log_expense()
view_expenses()Breaking the code into functions makes it easier to manage and reuse later