بايثون للجميع بجميع الأعمار: دليل سهل للمبتدئين

١٣ مايو ٢٠٢٣

Python for All Ages: An Accessible Guide for Beginners

مرحبًا بكم في هذه الرحلة الصديقة للمبتدئين إلى برمجة بايثون 🐍.
سنغطي مفاهيم بايثون الأساسية خطوة بخطوة مع أمثلة وأفضل الممارسات. سواء كنت طالبًا أو هاويًا أو محترفًا، فهذا الدليل سيجعل بايثون في متناول الجميع.

غلاف بايثون للمبتدئين


أولاً: هدف هذه المقالة

الهدف هو تقديم بايثون لك بطريقة بسيطة وجذابة.
سنفكك المفاهيم المعقدة إلى خطوات سهلة المتابعة مع عرض أمثلة من العالم الحقيقي.

  • كتابة كود بايثوني نظيف.
  • فهم أساسيات البرمجة كائنية التوجه.
  • التعامل مع الاستثناءات بفعالية.
  • إدارة الملفات والمجلدات والحزم.

ثانيًا: كتابة كود بايثوني

أ. التعبيرات الشاملة

تتيح التعبيرات الشاملة إنشاء هياكل البيانات بشكل موجز.

١. تعبير القائمة

squares = [x ** 2 for x in range(1, 11)]
print(squares)

٢. تعبير المجموعة

even_numbers = {x for x in range(1, 21) if x % 2 == 0}
print(even_numbers)

٣. تعبير القاموس

number_squares = {x: x ** 2 for x in range(1, 6)}
print(number_squares)

ب. دوال لامدا

دوال صغيرة وغير مسماة للمهام السريعة.

مثال: الترتيب حسب العنصر الثاني

pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)

مثال: تصفية الأعداد الزوجية

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

ج. معاملات الدالة (مع تلميحات النوع)

def greet(name: str = "Guest") -> None:
    print(f"Hello, {name}!")

greet()
greet("Alice")
def print_user_details(age: int, name: str) -> None:
    print(f"Name: {name}, Age: {age}")

print_user_details(age=25, name="Bob")
def product(x: int, y: int) -> int:
    return x * y

print(product(5, 3))

د. الوسائط المتغيرة

def sum_numbers(*args: int) -> int:
    return sum(args)

print(sum_numbers(1, 2, 3, 4, 5))
def print_user_details(**kwargs) -> None:
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_user_details(name="Alice", age=30, city="New York")

III. موجهات كائن بايثون

مخطط موجهات كائن بايثون

أ. المفاهيم الأساسية

  • الصفوف، الكائنات، الوراثة، تعدد الأشكال.
  • المزايا: وحدوية، إمكانية إعادة الاستخدام، سهولة الصيانة.

ب. الصفوف والكائنات

class Dog:
    species = "Canis lupus familiaris"  # Class variable

    def __init__(self, name: str, breed: str):
        self.name = name
        self.breed = breed

    def bark(self) -> None:
        print(f"{self.name} says woof!")

my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()

ج. كل شيء كائن

print(type(42))  
print(id(42))  

د. الوراثة

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        print("Woof!")

class Cat(Animal):
    def speak(self):
        print("Meow!")

dog = Dog()
cat = Cat()

dog.speak()
cat.speak()

هـ. التعددية الشكلية

def make_sound(animal: Animal):
    animal.speak()

make_sound(dog)
make_sound(cat)

رابعًا. معالجة الاستثناءات

معالجة استثناءات بايثون

أ. الاستثناءات المضمنة والمخصصة

try:
    int("abc")
except ValueError:
    print("Oops! A ValueError occurred.")
class CustomError(Exception):
    pass

try:
    raise CustomError("Custom issue")
except CustomError as e:
    print(f"Caught: {e}")

ب. المحاولة/استثناء/غير ذلك/في النهاية

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("No exceptions were raised.")
finally:
    print("This always runs.")

و. إدارة الملفات

Python Filesystem

أ. معالجة الملفات

from pathlib import Path

# Write
Path("output.txt").write_text("Hello, world!")

# Read
content = Path("output.txt").read_text()
print(content)

ب. المجلدات (باستخدام pathlib)

from pathlib import Path

path = Path("new_directory")
path.mkdir(exist_ok=True)
print(path.exists())

path.rmdir()

ج. الوحدات والחבوات

# my_module.py
def my_function():
    print("Hello from my_module!")

# Usage
import my_module
my_module.my_function()

Note: __init__.py هو اختياري في Python 3.3+, لكنه لا يزال مفيدًا للتعريف الصريح للحزمة.


سادسًا. الخلاصة

موجز

  • كود بايثوني: التجميعات، الدوال اللامبدية، args/kwargs.
  • برمجة كائنية التوجه: الفئات، الكائنات، الوراثة، تعدد الأشكال.
  • استثناءات: try/except/finally مع أفضل الممارسات.
  • الملفات والחבوات: إدخال/إخراج الملفات، المجلدات، الوحدات، الحبوات.

الخطوات التالية

  • استكشف المكتبات القياسية (itertools, functools, pathlib).
  • جرب إطارات الويب مثل Django أو Flask.
  • تعلم علوم البيانات باستخدام pandas و NumPy و PyTorch.
  • انضم إلى مجتمعات البرمجة والمسابقات البرمجية.
  • برمجة سعيدة! 🐍✨