أساسيات كتابة السكربتات بلغة Python

تحتاج إلى قدر كافٍ من Python لفهم الواجهة الخلفية في Flask. وإن كنت تعرف Python بالفعل، فيكفي أن تمرّ على هذه الصفحة مرورًا سريعًا.

تشغيل Python

# الوضع التفاعلي
python3
>>> print("hello")
hello
>>> exit()

# تشغيل سكربت
python3 myscript.py

المتغيرات والأنواع

name = "Alice"           # سلسلة نصية
age = 25                 # عدد صحيح
height = 5.6             # عدد عشري
is_student = True        # قيمة منطقية
hobbies = ["reading", "coding"]  # قائمة
person = {"name": "Alice", "age": 25}  # قاموس

print(type(name))        # <class 'str'>

السلاسل النصية

name = "Alice"
greeting = f"Hello, {name}!"   # f-string — استخدمها!
print(greeting)                # Hello, Alice!

# عمليات على النصوص
text = "  hello world  "
print(text.strip())           # "hello world"
print(text.upper())           # "  HELLO WORLD  "
print(len(text))              # 15
print(text.split())           # ["hello", "world"]

القوائم

fruits = ["apple", "banana", "cherry"]
fruits.append("date")         # إضافة إلى النهاية
fruits[0]                     # "apple" (الفهرس يبدأ من 0)
fruits[-1]                    # "date" (العنصر الأخير)
len(fruits)                   # 4

for fruit in fruits:
    print(fruit)

القواميس

person = {
    "name": "Alice",
    "age": 25,
    "city": "NYC"
}
print(person["name"])         # "Alice"
person["job"] = "engineer"    # إضافة مفتاح
person["age"] = 26            # تحديث القيمة

الجمل الشرطية

age = 18
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teen")
else:
    print("Child")

الحلقات التكرارية

# حلقة for على نطاق رقمي
for i in range(5):            # 0, 1, 2, 3, 4
    print(i)

# حلقة for على قائمة
for fruit in ["apple", "banana"]:
    print(fruit)

# حلقة while
count = 0
while count < 3:
    print(count)
    count += 1

الدوال

def greet(name, greeting="Hello"):
    """Return a greeting string."""
    return f"{greeting}, {name}!"

print(greet("Alice"))         # Hello, Alice!
print(greet("Bob", "Hi"))     # Hi, Bob!

قراءة الملفات وكتابتها

# الكتابة إلى ملف
with open("output.txt", "w") as f:
    f.write("Hello file!\n")

# القراءة من ملف
with open("output.txt", "r") as f:
    content = f.read()
    print(content)

# القراءة سطرًا سطرًا
with open("output.txt", "r") as f:
    for line in f:
        print(line.strip())

استيراد الوحدات

import math
print(math.sqrt(16))          # 4.0
print(math.pi)                # 3.14159...

import random
print(random.randint(1, 10))  # عدد عشوائي بين 1 و10

from datetime import datetime
print(datetime.now())         # التاريخ والوقت الحاليان

معالجة الأخطاء باستخدام try/except

try:
    number = int(input("Enter a number: "))
    print(100 / number)
except ValueError:
    print("That's not a number!")
except ZeroDivisionError:
    print("Can't divide by zero!")
except Exception as e:
    print(f"Something went wrong: {e}")

أداة pip (تثبيت الحزم)

pip install requests       # تثبيت حزمة
pip install flask          # تثبيت Flask
pip list                   # عرض الحزم المثبّتة
pip freeze > requirements.txt  # حفظ التبعيات
pip install -r requirements.txt  # التثبيت من ملف

دورك الآن — سكربت صغير

أنشئ الملف analyze.py:

import sys

def count_words(filename):
    """Count words in a file."""
    with open(filename, 'r') as f:
        content = f.read()
    words = content.split()
    return len(words)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python analyze.py <filename>")
    else:
        count = count_words(sys.argv[1])
        print(f"Word count: {count}")

شغّله:

echo "Hello world this is a test" > test.txt
python analyze.py test.txt
# → عدد الكلمات: 6