تتبع إنفاقك (أو عاداتك)
فهم كيفية تسجيل إدخال المنظمة في ملف.
لنقم بناء مشروع 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().
لقد أنشأت للتو سجل نفقات مستمر!
الخطوة الثانية: قراءة وعرض المصروفات
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