الوظائف#
مقدمة#
تُعدّ الدوال عنصرًا أساسيًا في برمجة بايثون، حيث تُجمّع أجزاءً من التعليمات البرمجية في أقسام قابلة لإعادة الاستخدام وفعّالة، مصممة لأداء مهمة محددة. يمكن استدعاء الدوال عدة مرات داخل البرنامج، مما يُسهّل تنظيم التعليمات البرمجية ويُساعد على تجنّب تكرارها. كما تُسهّل الدوال عملية تصحيح الأخطاء.
هام: تعريف الدالة وحده لا يكفي لتشغيلها. استخدم start_thread لبدء تشغيل الدالة في سلسلة عمليات جديدة، بحيث تبدأ بالعمل فور بدء المشروع، بدلاً من انتظار حدث أو رد نداء.
defيُعرّف دالة.returnيعيد مخرجات الدالة إلى البرنامج الرئيسي.
طريقة الاستخدام:
def function_name(parameters):
# Code to execute when the function is called
return result # Optional, used to return a value
حدود |
وصف |
|---|---|
|
اسم تطلقه على وظيفتك. |
|
اختياري. متغيرات تقبل قيم الإدخال عند استدعاء الدالة، مما يسمح بتمرير البيانات إلى الدالة. |
|
اختياري. يسمح للدالة بإعادة النتيجة إلى المُستدعي. إذا لم تتضمن الدالة عبارة إرجاع، فستُرجع القيمة |
Note: A function must always be defined before it is called.
تعريف واستدعاء الدوال#
Functions with No Parameters#
إذا لم تتطلب الدالة إدخالاً، فيمكنك تعريفها بدون معلمات.
def greeting():
console.print("Hello!")
def main():
# Call the greeting function
greeting()
# Start threads — Do not delete
start_thread(main)
Functions with Parameters#
يمكنك أيضًا إضافة معلمات إلى الدوال، مما يسمح لك بتمرير المعلومات التي تحتاجها الدالة للعمل.
# Build Used: Super Code Base 2.0
def move_square(moves):
for index in range(moves):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Call the move_square function
move_square(4)
# Start threads — Do not delete
start_thread(main)
Functions with Default Arguments#
الوسيط الافتراضي هو مُعامل يفترض قيمة افتراضية إذا لم يتم توفير قيمة في استدعاء الدالة لهذا الوسيط.
# Build Used: Super Code Base 2.0
def move_square(moves=4):
for index in range(moves):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Call the move_square function
move_square()
# Start threads — Do not delete
start_thread(main)
Return Values from Functions#
يمكن للدوال إرسال البيانات إلى المُستدعي باستخدام الكلمة المفتاحية return . وهذا يسمح لك بالتقاط المخرجات واستخدامها في برنامجك.
def times_two(number):
return number * 2
def main():
# Display the return value
console.print(times_two(2))
# Start threads — Do not delete
start_thread(main)
بدء الخيط#
start_thread يبدأ دالة في سلسلة رسائل جديدة بحيث تبدأ في العمل فور بدء المشروع.
إذا تم استخدام أكثر من start_thread ، فسيتم تشغيل الوظائف بشكل متزامن.
Usage:
start_thread(function)
حدود |
وصف |
|---|---|
|
اسم دالة تم تعريفها مسبقاً. |
# Build Used: Super Code Base 2.0
def move_square():
# Move in a square path
while True:
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def led_lights():
# Blink LED lights
while True:
bumper.set_color(GREEN)
wait(0.5, SECONDS)
bumper.set_color(RED)
wait(0.5, SECONDS)
# Start threads — Do not delete
start_thread(move_square)
start_thread(led_lights)