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

Arithmetic and String Operations العمليات الحسابية والعمليات على النصوص

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

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

  • Perform arithmetic operations (+, -, *, /) on numeric variables.
  • Apply string concatenation to combine text dynamically.
  • Use string formatting (f-strings) to inject variables into output sentences.
  • Identify and resolve common syntax errors related to operators.
  • إجراء العمليات الحسابية الأساسية (+، -، *، /) على المتغيرات الرقمية.
  • تطبيق دمج النصوص (Concatenation) لدمج النصوص بشكل ديناميكي.
  • استخدام صياغة النصوص (f-strings) لإدخال قيم المتغيرات داخل الجمل النصية.
  • تحديد وحل الأخطاء البرمجية الشائعة المتعلقة بالمعاملات وأنواع البيانات.

1. Arithmetic Operators and Expressions

Python allows you to perform mathematical calculations using standard arithmetic operators. When writing numerical expressions, Python follows the standard mathematical order of operations (PEMDAS/BODMAS): parentheses first, followed by exponentiation, multiplication and division, and finally addition and subtraction.

Operator Operation Python Code Example Evaluation Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division (Always floats) 10 / 5 2.0
Arithmetic Operations Pipeline
Figure 2.1: Visualizing how Python inputs numerical variables x and y into the arithmetic operations pipeline to produce sum, difference, product, and division results.
Mathematical Operations Glossary
Floating-Point Division: In Python, using the / operator always results in a decimal float value (e.g. 10 / 5 evaluates to 2.0, not 2).
Operator Precedence: The order in which Python evaluates parts of a mathematical expression (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).

2. String Concatenation

In addition to numbers, operators can sometimes be applied to strings. The addition operator (+) behaves differently when applied to strings: it performs concatenation, which joins two or more strings together end-to-end to form a single, unified string.

first_name = "Jane"
last_name = "Doe"
# Concatenating strings with a space in between
full_name = first_name + " " + last_name
print(full_name) # Outputs: Jane Doe
String Concatenation Mechanics
Figure 2.2: How string concatenation glues distinct words and space characters together in memory to build cohesive text outputs.
⚠️

Type mismatch error: You cannot concatenate a string and a number directly using the + operator. For example, "Age: " + 25 will raise a TypeError: can only concatenate str (not "int") to str.

3. f-Strings (Formatted String Literals)

To construct complex text dynamically, Python provides f-strings (formatted string literals). By placing the letter f directly before the opening quotation mark of a string, you can inject variables or expressions directly into the text using curly braces {} placeholders.

name = "Alice"
age = 25
# Injecting variables dynamically
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting) # Outputs: Hello, my name is Alice and I am 25 years old.
f-string Interpolation
Figure 2.3: f-string interpolation structure showing how variables are dynamically mapped into placeholder braces inside a formatted string.

4. Troubleshooting Syntax Errors

Common operator issues often stem from mismatched data types or incomplete expressions. Make sure you match quotes properly and always keep data types aligned when applying operators.

Incorrect Code (Mismatched Types):
# Attempting to combine str and int
score = 95
msg = "Your score is " + score
print(msg) # CRASHES!
Correct Code (Using f-strings):
# Using f-string solves type mismatch
score = 95
msg = f"Your score is {score}"
print(msg) # Safe & Clean!

1. المعاملات والتعبيرات الحسابية

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

المعامل العملية الحسابية مثال كود بايثون نتيجة التقييم
+ الجمع 10 + 5 15
- الطرح 10 - 5 5
* الضرب 10 * 5 50
/ القسمة (تنتج دائماً أرقاماً عشرية) 10 / 5 2.0
مخطط تدفق العمليات الحسابية
الشكل 2.1: تصور لكيفية إدخال المتغيرات الرقمية x و y في تدفق العمليات الحسابية لإنتاج نواتج الجمع، والطرح، والضرب، والقسمة.
قاموس العمليات الرياضية
القسمة العشرية (Floating-Point Division): في بايثون، يؤدي استخدام المعامل / دائماً إلى نتيجة رقم عشري (مثلاً: 10 / 5 تعطي 2.0 وليس 2).
أولوية المعاملات (Operator Precedence): الترتيب الذي تتبعه بايثون لحساب أجزاء المعادلة الرياضية (الأقواس، الأسس، الضرب والقسمة، ثم الجمع والطرح).

2. دمج النصوص (String Concatenation)

بالإضافة إلى الأرقام، يمكن استخدام بعض المعاملات مع النصوص. يعمل معامل الجمع (+) بشكل مختلف عند تطبيقه على النصوص: حيث يقوم بعملية الدمج، وهي ربط نصين أو أكثر ببعضهم البعض لتكوين نص واحد متصل.

first_name = "Jane"
last_name = "Doe"
# دمج النصوص مع إضافة مسافة بينهما
full_name = first_name + " " + last_name
print(full_name) # المخرج: Jane Doe
آلية دمج النصوص
الشكل 2.2: توضيح لكيفية دمج الكلمات والمسافات المختلفة في الذاكرة لتكوين نص نهائي متناسق.
⚠️

خطأ عدم تطابق الأنواع: لا يمكنك دمج نص مع رقم مباشرة باستخدام المعامل +. على سبيل المثال، محاولة دمج "Age: " + 25 ستؤدي لخطأ من نوع TypeError: can only concatenate str (not "int") to str.

3. صياغة النصوص (f-Strings)

لبناء جمل نصية معقدة وديناميكية، توفر بايثون ميزة f-strings. عن طريق وضع حرف f قبل علامات الاقتباس مباشرة، يمكنك تضمين متغيرات أو تعبيرات برمجية داخل النص مباشرة باستخدام الأقواس المجعدة {} كحوافظ مكانية.

name = "Alice"
age = 25
# إدراج المتغيرات ديناميكياً داخل النص
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting) # المخرج: Hello, my name is Alice and I am 25 years old.
بناء جملة f-string
الشكل 2.3: هيكل صياغة f-string يوضح كيف يتم وضع المتغيرات مباشرة في الأماكن المحجوزة لها داخل السلسلة النصية.

4. إصلاح أخطاء الصياغة (Syntax Errors)

تنشأ معظم أخطاء المعاملات والنصوص من محاولة دمج أنواع بيانات مختلفة دون تحويل، أو نسيان علامات الاقتباس. احرص دائماً على تطابق علامات الاقتباس وتناسق أنواع البيانات.

كود خاطئ (عدم تطابق الأنواع):
# محاولة دمج نص مع عدد صحيح مباشرة
score = 95
msg = "Your score is " + score
print(msg) # يتوقف البرنامج بسبب خطأ!
كود صحيح (باستخدام f-strings):
# استخدام f-string يحل مشكلة دمج الأنواع
score = 95
msg = f"Your score is {score}"
print(msg) # يعمل بأمان وسهولة!
Practical Activity النشاط العملي

Receipt Generator منشئ فواتير الشراء

Build a simple product checkout script. Store item details, compute totals, and format a beautiful receipt output:

  1. Create variables item_name (string), price (float), and quantity (integer).
  2. Calculate the subtotal using arithmetic multiplication.
  3. Construct a formatted f-string receipt showing the item name, unit price, quantity, and total cost.
  4. Execute the program to ensure the variables print out accurately.

اكتب برنامجاً بسيطاً لحساب تكلفة شراء منتج. قم بتخزين تفاصيل المنتج، حساب التكلفة الكلية، ثم طباعة فاتورة منسقة بشكل احترافي:

  1. أنشئ المتغيرات التالية: item_name (نص)، price (رقم عشري لل سعر)، و quantity (عدد صحيح للكمية).
  2. احسب المجموع الفرعي subtotal باستخدام الضرب الحسابي.
  3. قم بصياغة فاتورة شراء باستخدام f-string تعرض اسم المنتج، سعر الوحدة، الكمية، والتكلفة الإجمالية.
  4. قم بتشغيل البرنامج وتأكد من طباعة النتائج بدقة ووضوح.
Model Answer (Python Code)
الإجابة النموذجية (كود بايثون)
# Step 1: Initialize variables
item_name = "Wireless Mouse"
price = 24.99
quantity = 3

# Step 2: Calculate subtotal
subtotal = price * quantity

# Step 3: Print structured receipt using f-strings
print("----- CHECKOUT RECEIPT -----")
print(f"Product:  {item_name}")
print(f"Price:    ${price} each")
print(f"Quantity: {quantity}")
print("----------------------------")
print(f"Total:    ${subtotal}")
print("----------------------------")

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. تتبع مخرجات المتغيرات ومسار المنطق للتأكد من عمل الكود بالشكل الصحيح.