Overall Course Progress التقدم الإجمالي في الدورة 0%
0 of 15 Days Completed تم إكمال 0 من 15 يوماً Target: 1 Hour/Day المستهدف: ساعة/يوم
Day 13 اليوم 13

Function Parameters and Returns معاملات الدوال البرمجية وقيم الإرجاع

Practical عملي 1 Hour 1 ساعة

Learning Outcomes مخرجات التعلم

  • Define functions that accept multiple parameters (arguments).
  • Pass variables into functions dynamically during execution.
  • Use the 'return' statement to output processed data back to the main program.
  • Capture and utilize returned values to update lists or print outputs.
  • تعريف دوال برمجية تستقبل معاملات متعددة (Parameters).
  • تمرير متغيرات وقيم حقيقية (Arguments) إلى الدوال ديناميكياً أثناء التنفيذ.
  • استخدام جملة الإرجاع 'return' لإخراج البيانات المعالجة من الدالة إلى البرنامج الرئيسي.
  • استقبال واستخدام القيم الراجعة من الدوال لتحديث القوائم أو طباعة المخرجات.

1. Parameters vs Arguments

Functions become much more useful when we can pass data into them. We do this using **parameters** and **arguments**:

  • Parameters: The placeholder variables listed inside the parentheses in the function's definition header (e.g. a and b in def add(a, b):).
  • Arguments: The actual, concrete values you pass into the function when you call it (e.g. 5 and 10 in add(5, 10)).
# a and b are parameters
def show_sum(a, b):
    print(f"Sum: {a + b}")

# 5 and 10 are arguments passed to the parameters a and b
show_sum(5, 10) # Outputs: Sum: 15
Parameters and Arguments mapping
Figure 13.1: Mapping arguments to parameters: showing how argument values passed in during a function call align with the parameter placeholders.
Parameters & Returns Glossary
Parameter: A placeholder variable in a function header definition.
Return Statement: A special statement (return) that terminates a function and sends a resulting value back to the caller.

2. The Return Statement Pipeline

So far, our functions have only printed results to the console. However, a function often needs to process data and send the result back to the main program so it can be stored in a variable or used in further calculations. We do this using the return statement.

When Python encounters a return statement, it stops executing the function immediately and passes the specified value back to the line of code that called the function.

# Returning a value
def multiply(x, y):
    return x * y # Returns the product to the caller

result = multiply(4, 5) # result gets assigned the value 20
print(result) # Outputs: 20
Function Returns Pipeline
Figure 13.2: The return data pipeline: input values flow in, get processed, and the return keyword sends the final output back to the calling code.

3. Capturing and Utilizing Return Values

If you call a function that returns a value but do not assign it to a variable or print it, that returned value is simply discarded. To use it, you must capture it:

def calculate_tax(amount):
    return amount * 0.15

# Capturing the returned tax value
tax_amount = calculate_tax(100)
total_cost = 100 + tax_amount
print(f"Total is: {total_cost}") # Outputs: Total is: 115.0
Capturing Return Values
Figure 13.3: Capturing function outputs: assigning the resulting value of a function call to a variable for future logic checks.
⚠️

Code after return: Any code placed inside a function *after* a return statement will never run. The return keyword exits the function immediately.

4. Resolving Return vs Print Logical Bugs

Beginners often confuse print() and return. Printing displays a value on the screen, but does not allow variables to capture it.

Incorrect Code (Print instead of Return):
def add(x, y):
    print(x + y) # Just prints, returns None!

ans = add(5, 5)
final = ans * 2 # CRASHES! TypeError: unsupported operand type for NoneType
Correct Code (Using Return):
def add(x, y):
    return x + y # Correctly outputs value

ans = add(5, 5)
final = ans * 2 # Works! final is 20

1. المعاملات (Parameters) مقابل القيم الممررة (Arguments)

تصبح الدوال أكثر فائدة عندما نتمكن من تمرير البيانات إليها. نقوم بذلك باستخدام المعاملات و القيم الحقيقية:

  • المعاملات (Parameters): متغيرات نكتبها كحوافظ مكانية داخل قوسي رأس تعريف الدالة (مثال: a و b في def add(a, b):).
  • القيم الممررة (Arguments): القيم الحقيقية والفعلية التي نمررها للدالة عند استدعائها (مثال: 5 و 10 في add(5, 10)).
# a و b هما المعاملان
def show_sum(a, b):
    print(f"Sum: {a + b}")

# 5 و 10 هما القيمتان الممررتان للمعاملين a و b
show_sum(5, 10) # المخرج: Sum: 15
خريطة المعاملات والقيم
الشكل 13.1: مطابقة القيم الممررة بالمعاملات: يوضح كيف تطابق القيم الفعلية المحددة أثناء استدعاء الدالة مع المتغيرات الافتراضية المحددة في رأس الدالة.
قاموس المعاملات وقيم الإرجاع
المعامل (Parameter): متغير نضعه كحافظة مكانية في رأس الدالة عند تعريفها.
جملة الإرجاع (Return Statement): جملة خاصة (return) تنهي عمل الدالة وتعيد القيمة الناتجة عنها إلى مكان استدعائها.

2. آلية عمل جملة الإرجاع (Return)

حتى الآن، كانت دوالنا تطبع النتائج فقط في لوحة التحكم. ومع ذلك، تحتاج الدالة في كثير من الأحيان لمعالجة البيانات وإرسال النتيجة للبرنامج الرئيسي لحفظها في متغير أو استخدامها في حسابات أخرى. نقوم بذلك باستخدام جملة return.

عندما تواجه بايثون جملة return، فإنها توقف تنفيذ الدالة فوراً وتمرر القيمة المحددة إلى السطر الذي استدعى الدالة.

# إرجاع القيمة
def multiply(x, y):
    return x * y # تعيد ناتج الضرب لمكان الاستدعاء

result = multiply(4, 5) # يتم تخصيص القيمة 20 للمتغير result
print(result) # المخرج: 20
مسار إرجاع القيم
الشكل 13.2: تدفق إرجاع البيانات: تدخل القيم للدالة، تتم معالجتها، ويرسل أمر return النتيجة النهائية للبرنامج الرئيسي.

3. استقبال واستخدام القيم الراجعة

إذا استدعيت دالة تعيد قيمة ولكنك لم تخصصها لمتغير أو تطبعها، فستضيع القيمة الناتجة. يجب عليك حفظها لاستخدامها:

def calculate_tax(amount):
    return amount * 0.15

# استقبال القيمة الراجعة للضريبة
tax_amount = calculate_tax(100)
total_cost = 100 + tax_amount
print(f"Total is: {total_cost}") # المخرج: Total is: 115.0
حفظ القيمة الراجعة
الشكل 13.3: استقبال مخرجات الدوال: تخصيص القيمة الناتجة عن استدعاء الدالة لمتغير لاستخدامه في التحقق الحسابي لاحقاً.
⚠️

الأكواد بعد return: أي كود مكتوب داخل الدالة *بعد* سطر return لن يعمل أبداً. فأمر return ينهي عمل الدالة ويغادرها فوراً.

4. الفرق المنطقي بين الطباعة (Print) والإرجاع (Return)

يخلط المبتدئون كثيراً بين الطباعة print() والإرجاع return. تعرض الطباعة القيمة على الشاشة فقط، ولكنها لا تمنح المتغيرات القدرة على حفظها واستخدامها.

كود خاطئ (طباعة بدلاً من إرجاع):
def add(x, y):
    print(x + y) # يطبع فقط، ويعيد None افتراضياً!

ans = add(5, 5)
final = ans * 2 # يتوقف البرنامج! TypeError: unsupported operand type for NoneType
كود صحيح (استخدام return):
def add(x, y):
    return x + y # يعيد القيمة بشكل صحيح

ans = add(5, 5)
final = ans * 2 # يعمل بنجاح! final تساوي 10
Practical Activity النشاط العملي

Bilingual Discount Calculator حاسبة الخصم التفاعلية

Write a script containing a function that calculates discount values and returns the net price:

  1. Define a function named get_discount_price(original_price, discount_percent).
  2. Inside the function, calculate the discount amount: original_price * (discount_percent / 100).
  3. Subtract the discount amount from the original price to compute the discounted_price.
  4. Return the discounted_price value.
  5. Call the function passing 120 as price and 20 as discount percentage. Capture the returned value in a variable and print the final price in a descriptive f-string.

اكتب برنامجاً يحتوي على دالة تقوم بحساب نسبة الخصم وإرجاع السعر النهائي بعد التخفيض:

  1. عرف دالة باسم get_discount_price(original_price, discount_percent).
  2. احسب قيمة الخصم داخل الدالة: original_price * (discount_percent / 100).
  3. اطرح قيمة الخصم من السعر الأصلي لحساب السعر النهائي بعد الخصم discounted_price.
  4. قم بإرجاع قيمة السعر النهائي discounted_price باستخدام return.
  5. استدعى الدالة ممرراً لها السعر 120 ونسبة الخصم 20. استقبل القيمة الراجعة في متغير واطبع السعر النهائي بجملة توضيحية.
Model Answer (Python Code)
الإجابة النموذجية (كود بايثون)
# Step 1: Define function with parameters and return
def get_discount_price(original_price, discount_percent):
    discount_amount = original_price * (discount_percent / 100)
    discounted_price = original_price - discount_amount
    return discounted_price  # Return result back to program

# Step 2: Call function and capture returned value
price = 120.0
discount = 20.0
final_price = get_discount_price(price, discount)

# Step 3: Print result
print(f"Original Price: ${price}")
print(f"Discount:       {discount}%")
print(f"Discounted Price: ${final_price}")

Run the code above in your Thonny or VS Code IDE. Inspect variable outputs and logic flow to ensure it behaves exactly as described. قم بتشغيل الكود أعلاه في بيئة Thonny أو VS Code. تتبع مخرجات المتغيرات ومسار المنطق للتأكد من عمل الكود بالشكل الصحيح.