تعريف الدوال البرمجية (def)
رأيت من قبل كيف تستدعي دوال مثل print() وlen(). الآن ستتعلم كيف تكتب دوالك الخاصة بحيث تستطيع أنت أو غيرك استخدامها. تصبح هذه الفكرة شديدة الأهمية كلما كبر البرنامج وزاد تعقيده.
إليك مثالًا بسيطًا:
def greet(name):
print(f'Hello {name}!')
greet('Alice')
greet('Bob')
هذا الكود يعرّف دالة اسمها greet تستقبل معاملًا واحدًا. وبعد تعريف الدالة نستدعيها مرتين. شغّل الكود ولاحظ ما يحدث.
تعريف الدالة عبارة مركبة (compound statement). وكما في if وfor، يبدأ بسطر رأس (header) ثم جسم مزاح إلى الداخل يمكن أن يحتوي على تعليمة واحدة أو أكثر.
أضف تعليمة أخرى إلى الدالة حتى تصبح هكذا:
def greet(name): print(f"Hello {name}!") print("How are you?") ثم شغّل البرنامج مرة أخرى.
لاحظ كيف تغيّر ناتج البرنامج. أصبحت How are you? تُطبع مرتين. يمكنك التفكير في البرنامج كله كما لو كان مكافئًا تقريبًا لما يلي:
name = "Alice" print(f"Hello {name}!") print("How are you?")
name = "Bob" print(f"Hello {name}!") print("How are you?") وهذا يوضح واحدة من أهم فوائد الدوال: يمكنك إعادة استخدام الكود نفسه مرات عديدة من دون تكرار كتابته. الأمر يشبه كتابة برنامج صغير داخل برنامج أكبر.
سطر رأس تعريف الدالة يحتوي دائمًا على هذه الأجزاء:
- الكلمة المحجوزة
defثم مسافة. - اسم الدالة. يشبه اسم المتغير: يمكنك اختيار الاسم، مع وجود قيود مثل عدم احتوائه على مسافة.
- قوسان
(و). - صفر أو أكثر من أسماء المعاملات بين القوسين، مفصولة بفواصل إذا كان هناك أكثر من معامل. هنا لدينا معامل واحد اسمه
name. - النقطتان
:.
لنجرّب تمرينًا بسيطًا. غيّر اسم الدالة من greet إلى say_hello. يجب أن يظل البرنامج كله يعمل بالطريقة نفسها، ولا تغيّر أي شيء آخر.
You have to change the name in the function definition header, but that's not all.
If you just change the name in the function definition header, what happens?
You get an error. Look at the message. What is it telling you? Where does the error come from?
If your function is called
say_hello, what doesgreet("Alice")mean?You need to change exactly 3 lines of the program.
In each line you change, change exactly one word.
Don't touch the body of the function. It should still have
print("How are you?").You should still call the function twice after defining it, with arguments
"Alice"and"Bob".
جيد! الآن طبّق فكرة مشابهة: غيّر اسم المعامل من name إلى person_name.
تذكّر أن تغيير اسم المعامل في رأس الدالة وحده لا يكفي إذا كان جسم الدالة ما زال يشير إلى الاسم القديم. عدّل كل المواضع اللازمة فقط، واترك استدعاءات say_hello("Alice") وsay_hello("Bob") كما هي.
You have to change the parameter name in the function definition header, but that's not all.
If you just change the parameter name in the function definition header, what happens?
You get an error. Look at the message. What is it telling you? Where does the error come from?
If the parameter is called
person_name, what doesprint(f"Hello {name}!")mean?You need to change exactly 2 lines of the program.
In each line you change, change exactly one word.
Don't touch the part after the function definition, i.e.
say_hello("Alice")andsay_hello("Bob").You should still have two statements in the function body, including
print("How are you?").
أحسنت!
اكتب الآن دالة خاصة بك اسمها print_twice تستقبل معاملًا واحدًا x وتطبع هذا المعامل مرتين، كل مرة في سطر منفصل.
مثلًا، الاستدعاء print_twice("Hello") يجب أن يطبع:
Hello Hello يمكنك اختبار الدالة باستدعائها بعد تعريفها، لكن ذلك ليس مطلوبًا ضمن تعريف الدالة نفسه.
There's no clever problem solving here, this is just about following the recipe for defining a function.
Make sure you have all the parts of a function listed above.
That includes
def,(), and:.Make sure your function is named
print_twice.Make sure it accepts one parameter called
xin between the parentheses().Look at the other functions defined above for help.
Use the parameter inside the function body.
Make sure the body is indented.
The body needs two statements or a very simple loop.
Make sure that you don't call
print_twiceinside the function body ofprint_twice. Check your indentation.
يمكن أن تستقبل الدالة أكثر من معامل واحد. جرّب المثال التالي:
def print_many(thing, n):
for _ in range(n):
print(thing)
print_many('Hello', 3)
راقب كيف تُستخدم القيم الممررة عند استدعاء الدالة داخل جسمها.
لاحظ الفواصل التي تفصل المعاملات في تعريف الدالة، والفواصل التي تفصل الوسائط عند الاستدعاء، والعلاقة بين ترتيب الطرفين:
def print_many(thing, n):
^ ^
| |
print_many("Hello", 3)
لذلك يمكن التفكير في print_many("Hello", 3) كما لو أنه يؤدي في بداية الاستدعاء إلى:
thing = "Hello" n = 3 for _ in range(n): print(thing) في هذا التمرين، بدّل ترتيب المعاملات في رأس تعريف الدالة ليصبح:
def print_many(n, thing): إذا فعلت ذلك وحده سيظهر خطأ أو سلوك غير صحيح. أصلح بقية البرنامج بحيث يتصرف كما كان من قبل. لا تغيّر جسم الدالة.
The only change to the function definition should be the swapping of parameters as instructed, nothing else.
You need to fix the call to
print_many.If the function is defined as
def print_many(n, thing), what doesprint_many("Hello", 3)mean?We still want
thing = "Hello"andn = 3.
ممتاز! لديك الآن أساس قوي لفهم كيفية تعريف الدوال في بايثون.