الأسبوع التاسع · الصف العاشر

الأخطاء
والاستثناءات

البرنامج وقف فجأة؟! لا تخاف: نتعلم نصيد الخطأ ونصلّحه try · except · Debugتصحيح الأخطاء والاستثناءات Exceptions and Debugging: ص137-152
صف الحصة
مشكلة 😵

البرنامج
وقف فجأة!

المستخدم يشوف شاشة حمراء وخلاص؟! الحل: معالجة الأخطاءالتعامل مع الأخطاء بطريقة منظمة تمنع توقف البرنامج (ص137)
ص137

ليش
نتعلمها؟

الأخطاء Errors والاستثناءات Exceptions: مفهوم أساسي في البرمجة(ص137)
أخطاء PyCharm

PyCharm
يكشف الخطأ

ثلاث علامات تدل على وجود خطأ في الكود (ص137)
تصحيح (ص138)

نصلّح
الخطأ

ص138

أنواع
الأخطاء

ثلاثة أنواع رئيسة: لغوية، وقت التشغيل، منطقيةالشكل 3-6 (ص138)
النوع 1

الأخطاء
اللغوية

Syntax Errors: تظهر قبل بدء التنفيذ لأن المفسّر ما يفهم الكود(ص139)
أمثلة (ص139)

مخالفة
قواعد الكتابة

نسيان الأقواس أو النقطتين أو علامات التنصيص، أو كتابة الكلمات المفتاحية بشكل خاطئ (ص139)
النوع 2

أخطاء
وقت التشغيل

Runtime Errors: الكتابة سليمة، بس يصير خطأ أثناء التنفيذ(ص139-140)
أمثلة (ص140)

أشهر أخطاء
وقت التشغيل

النوع 3

الأخطاء
المنطقية

Logic Errors: الكود يشتغل بدون أي رسالة، بس النتيجة غلط(ص140-141)
أمثلة (ص141)

يشتغل
والنتيجة غلط

قارن

الأنواع
الثلاثة

لغوي قبل التنفيذ، وقت التشغيل أثناءه، والمنطقي ما يعطي رسالةص139-141
تدريب 🎯

صنّف
الخطأ

الاستثناءات (ص142)

try يعني
جرّب

try جرّب · except لو غلط · else لو ما غلط · finally دائماً (ص142)
مثال 1

حاسبة
الرحلة

يستقبل تكلفة الرحلة وعدد الطلاب ويحسب مشاركة كل طالب (ص142)
تتبّع

ثلاث
تجارب

مثال 2

استثناء
شامل

ملاحظات (ص145)

محدد
أو شامل؟

المحدد أفضل لأنه يسهّل تتبع الأخطاء وفهمهاملاحظات (ص145)
مثال 3

زوجي
أو فردي

ص146

Debug يعني
تتبّع

عملية تتبع وتحليل التعليمات البرمجية خطوة بخطوة لاكتشاف الأخطاء وفهم سير التنفيذ، بهدف تصحيح النتائج غير المتوقعةتصحيح الأخطاء Debugging (ص146)
خطوات PyCharm

نقطة توقف
و Debug

خطوات تتبع وتحليل الأخطاء في PyCharm (ص146-147)
أدوات (ص147)

أدوات
التصحيح

تطبيق

نتتبّع
الخطأ المنطقي

ورقة عمل 16

فاتورة
بعد الخصم

برنامج يحسب السعر بعد الخصم، ويتحقق من المدخلات بـ try / exceptورقة عمل 16 (ص149-150)
price_discount.py — PyCharm
1try:
2 price = float(input("Enter price: "))
3 discount = float(input("Enter discount (%): "))
4 if price <= 0:
5 print("Error: Price must be greater than zero")
6 elif discount < 0 or discount > 100:
7 print("Error: Discount must be between 0% and 100%")
8 else:
9 price_net = price - (price * discount / 100)
10 print("Net price after discount is:", price_net)
11except ValueError:
12 print("Error: Please enter valid numeric values.")
13finally:
14 print("Program has ended")
حل جاهز

ورقة عمل 16
فاتورة بعد الخصم

try يحمي التحويل لعدد، و if / elif / else تتأكد من السعر والخصم (ص150)
finally تطبع الرسالة النهائية في كل الأحوال (ص149)
تجربة: 200 ثم 25
Enter price: 200
Enter discount (%): 25
Net price after discount is: 150.0
Program has ended
تجربة: abc
Enter price: abc
Error: Please enter valid numeric values.
Program has ended
تجربة: 100 ثم 150
Enter price: 100
Enter discount (%): 150
Error: Discount must be between 0% and 100%
Program has ended
ورقة عمل 17

مؤشر كتلة
الجسم BMI

اكتشاف الأخطاء وتجاوزها: استكمل البرنامج ليعمل بصورة صحيحةورقة عمل 17 (ص151-152)
BMI.py — PyCharm
1while True:
2 try:
3 weight = float(input("Enter weight (kg): "))
4 height = float(input("Enter height (m): "))
5 bmi = weight / (height ** 2)
6 print(f"BMI: {bmi:.2f}")
7 if bmi < 18.5:
8 print("You are underweight.")
9 elif bmi < 25:
10 print("You have a normal weight.")
11 elif bmi < 30:
12 print("You are overweight.")
13 else:
14 print("You are obese.")
15 except ValueError:
16 print("Error: Please enter valid numeric values for weight and height.")
17 except ZeroDivisionError:
18 print("Error: You can't divide by zero!")
حل جاهز

ورقة عمل 17
مؤشر كتلة الجسم

while True يعيد البرنامج من الخطوة 2 بعد كل نتيجة أو خطأ (ص151)
except ValueError و except ZeroDivisionError: البرنامج ما يوقف (ص151)
تجربة: 70 و 1.75 ثم seventy ثم 70 و 0
Enter weight (kg): 70
Enter height (m): 1.75
BMI: 22.86
You have a normal weight.
Enter weight (kg): seventy
Error: Please enter valid numeric values for weight and height.
Enter weight (kg): 70
Enter height (m): 0
Error: You can't divide by zero!
Enter weight (kg):
الملخص

البرنامج كامل،
قطعة قطعة

🏆 لوحة النقاط
↩ رجوع للشريحة 1
⬇ تصدير Excel
💾 نسخة احتياطية
📂 استرجاع نسخة
كل ضغطة = نص نقطة
1x = 5
2print(x))
1x = 5
2print(x)
1x = 5
2if x > 0
3 print(x)
1print("Hello, Kuwait!"
1for i in range(5):
2print(i)
1print(5 / 0)
1x = 5
2print(z)
1print('5' + 10)
1number = int('abc')
1length = 5
2width = 4
3area_rectangle = length + width
4print(area_rectangle)
1length = 5
2width = 4
3area_rectangle = length * width
4print(area_rectangle)
1a = b = c = 10
2average = a + b + c / 3
3print(average)
1a = b = c = 10
2average = (a + b + c) / 3
3print(average)
1score = 45
2if score < 50:
3 print("Excellent")
1score = 45
2if score < 50:
3 print("Fail")
1try:
2 # Code that might cause an error
3except ErrorType:
4 # Code to execute if an error occurs
5else:
6 # Code to execute if no error occurs
7finally:
8 # Code that always executes
1try:
2 print("School Trip Cost Sharing Calculator")
3 cost_total = float(input("Enter total trip cost (KWD): "))
4 students = int(input("Number of participating students: "))
5 share = cost_total / students
6except ValueError:
7 print("Input Error: Please enter valid numbers only!")
8except ZeroDivisionError:
9 print("Error: Cannot divide by zero - please check student count")
10else:
11 print(f"Each student's share: {share:.2f} KWD")
12finally:
13 print("Program ended!")
1try:
2 print("School Trip Cost Sharing Calculator")
3 cost_total = float(input("Enter total trip cost (KWD): "))
4 students = int(input("Number of participating students: "))
5 share = cost_total / students
6except ValueError:
7 print("Input Error: Please enter valid numbers only!")
8except ZeroDivisionError:
9 print("Error: Cannot divide by zero - please check student count")
10else:
11 print(f"Each student's share: {share:.2f} KWD")
12finally:
13 print("Program ended!")
1try:
2 print("School Trip Cost Sharing Calculator")
3 cost_total = float(input("Enter total trip cost (KWD): "))
4 students = int(input("Number of participating students: "))
5 share = cost_total / students
6except ValueError:
7 print("Input Error: Please enter valid numbers only!")
8except ZeroDivisionError:
9 print("Error: Cannot divide by zero - please check student count")
10else:
11 print(f"Each student's share: {share:.2f} KWD")
12finally:
13 print("Program ended!")
1try:
2 print("School Trip Cost Sharing Calculator")
3 cost_total = float(input("Enter total trip cost (KWD): "))
4 students = int(input("Number of participating students: "))
5 share = cost_total / students
6except ValueError:
7 print("Input Error: Please enter valid numbers only!")
8except ZeroDivisionError:
9 print("Error: Cannot divide by zero - please check student count")
10else:
11 print(f"Each student's share: {share:.2f} KWD")
12finally:
13 print("Program ended!")
1try:
2 print("School Trip Cost Sharing Calculator")
3 cost_total = float(input("Enter total trip cost (KWD): "))
4 students = int(input("Number of participating students: "))
5 share = cost_total / students
6 print(f"Each student's share: {share:.2f} KWD")
7except Exception as e:
8 print('Error is:', e)
9finally:
10 print("Program ended!")
1while True:
2 try:
3 number = int(input('Enter a number:'))
4 if number % 2 == 0:
5 print('The number is even.')
6 else:
7 print('The number is odd.')
8 except ValueError:
9 print('You did not enter a valid number.')
1try:
2 n = int(input("Enter a number: "))
3 print(100 / n)
4except ValueError:
5 print("Not a number")
6except ZeroDivisionError:
7 print("Cannot divide by zero")
8finally:
9 print("Done")
▶ Run
File "main.py", line 2
SyntaxError: unmatched ')'
Process finished with exit code 1
5
File "main.py", line 2
SyntaxError: expected ':'
Process finished with exit code 1
File "main.py", line 1
SyntaxError: '(' was never closed
Process finished with exit code 1
File "main.py", line 2
IndentationError: expected an indented block after 'for' statement on line 1
Process finished with exit code 1
Traceback (most recent call last):
File "main.py", line 1, in <module>
ZeroDivisionError: division by zero
Process finished with exit code 1
Traceback (most recent call last):
File "main.py", line 2, in <module>
NameError: name 'z' is not defined
Process finished with exit code 1
Traceback (most recent call last):
File "main.py", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
Traceback (most recent call last):
File "main.py", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
Process finished with exit code 1
9
20
23.333333333333332
10.0
Excellent
Fail
School Trip Cost Sharing Calculator
Enter total trip cost (KWD): 12
Number of participating students: 4
Each student's share: 3.00 KWD
Program ended!
School Trip Cost Sharing Calculator
Enter total trip cost (KWD): abc
Input Error: Please enter valid numbers only!
Program ended!
School Trip Cost Sharing Calculator
Enter total trip cost (KWD): 1.5
Number of participating students: 0
Error: Cannot divide by zero - please check student count
Program ended!
School Trip Cost Sharing Calculator
Enter total trip cost (KWD): 10
Number of participating students: 0
Error is: float division by zero
Program ended!
Enter a number:56
The number is even.
Enter a number:8.9
You did not enter a valid number.
Enter a number:11GR
You did not enter a valid number.
Enter a number:
Enter a number: 0
Cannot divide by zero
Done
1 / 30
‹
›
↻
🏆 النقاط