FSc Part 2 Computer Science Chapter 5 Complete Guide Book — Code Testing and Debugging | PunjabTest.com

FSc Part 2 Computer Science Chapter 5 — Code Testing and Debugging
Home > PunjabTest.com > FSc Part 2 > Computer Science — all chapters > Chapter 5: Code Testing and Debugging

اس chapter میں topics (Topics in this chapter)

1. 🧪 Introduction — Testing and Debugging Techniquesتعارف — ٹیسٹنگ اور ڈی بگنگ کی تکنیکیں
🏷 Tags: Introduction, Testing, Debugging, Techniques
ENGLISH

In this chapter, students learn the essential techniques of code testing and debugging to ensure their programs function correctly. They understand the importance of testing for creating reliable applications and explore common types of programming errors and bugs. The chapter covers unit testing using Python's unittest and pytest modules, debugging with breakpoints, watch expressions, and step-by-step debugging, exception handling for multiple exception types, and profiling and optimization to measure performance and identify bottlenecks.

Testing and Debugging Techniques: advanced testing and debugging techniques help create reliable and efficient applications. They go beyond basic error fixing to ensure program quality. These techniques identify hidden problems that may affect functionality. Testing and debugging improve performance and user satisfaction, and make future maintenance easier.

Importance of Testing and Debugging: testing and debugging are essential to ensure applications work correctly under all conditions. They help detect and remove errors before the software is released. Regular testing prevents unexpected failures during operation. Debugging locates the cause of errors and fixes them efficiently. Together, these practices increase reliability and user confidence.

Why testing is essential for reliable applications: testing checks whether an application meets its requirements. It ensures that all functions produce correct results. Testing reduces the risk of crashes or incorrect outputs. It also helps verify that changes do not break existing features. Applications that are thoroughly tested are more trustworthy and stable.

Common types of programming errors and bugs: Syntax errors occur when code does not follow language rules — e.g. missing a colon: if x > 5 (no colon) → SyntaxError: invalid syntax; the program fails to run because the Python syntax is wrong. Correct: if x > 5: print("x is greater"). Logic errors happen when the program produces incorrect results — e.g. length = 5, width = 3, area = length + width gives 8 (incorrect); correct logic area = length × width gives 15. The program runs, but the result is wrong because the formula is incorrect. Runtime errors appear while the program is running — e.g. a = 10, b = 0, result = a / b → ZeroDivisionError: division by zero; the program stops during execution because an invalid operation occurs. Other common bugs include data errors and resource leaks. Identifying these errors is key to building stable applications.

اردو

اس باب میں طلبہ کوڈ ٹیسٹنگ اور ڈی بگنگ کی ضروری تکنیکیں سیکھتے ہیں تاکہ ان کے پروگرام درست کام کریں۔ وہ قابل اعتماد ایپلی کیشنز بنانے کے لیے ٹیسٹنگ کی اہمیت سمجھتے ہیں اور پروگرامنگ کی غلطیوں اور بگز کی عام اقسام کا جائزہ لیتے ہیں۔ باب میں پائتھون کے unittest اور pytest ماڈیولز سے یونٹ ٹیسٹنگ، بریک پوائنٹس، واچ ایکسپریشنز اور مرحلہ وار ڈی بگنگ سے ڈی بگنگ، کئی ایکسیپشن اقسام کے لیے ایکسیپشن ہینڈلنگ، اور کارکردگی ناپنے اور رکاوٹیں پہچاننے کے لیے پروفائلنگ اور آپٹیمائزیشن شامل ہے۔

ٹیسٹنگ اور ڈی بگنگ کی تکنیکیں: جدید ٹیسٹنگ اور ڈی بگنگ کی تکنیکیں قابل اعتماد اور مؤثر ایپلی کیشنز بنانے میں مدد دیتی ہیں۔ یہ بنیادی غلطی درست کرنے سے آگے بڑھ کر پروگرام کے معیار کو یقینی بناتی ہیں۔ یہ تکنیکیں چھپی ہوئی مسائل کی نشاندہی کرتی ہیں جو فعالیت پر اثر ڈال سکتے ہیں۔ ٹیسٹنگ اور ڈی بگنگ کارکردگی اور صارف کی اطمینان بہتر کرتے ہیں، اور مستقبل کی دیکھ بھال آسان بناتے ہیں۔

ٹیسٹنگ اور ڈی بگنگ کی اہمیت: ٹیسٹنگ اور ڈی بگنگ ضروری ہیں تاکہ ایپلی کیشنز تمام حالات میں درست کام کریں۔ یہ سافٹ ویئر جاری ہونے سے پہلے غلطیاں ڈھونڈنے اور ہٹانے میں مدد دیتے ہیں۔ باقاعدہ ٹیسٹنگ آپریشن کے دوران غیر متوقع ناکامیاں روکتی ہے۔ ڈی بگنگ غلطیوں کی وجہ ڈھونڈ کر انہیں مؤثر طریقے سے ٹھیک کرتی ہے۔ مل کر یہ طریقے قابل اعتمادیت اور صارف کا اعتماد بڑھاتے ہیں۔

قابل اعتماد ایپلی کیشنز کے لیے ٹیسٹنگ کیوں ضروری ہے: ٹیسٹنگ چیک کرتی ہے کہ آیا ایپلی کیشن اپنی ضروریات پوری کرتی ہے۔ یہ یقینی بناتی ہے کہ تمام فنکشنز درست نتائج دیں۔ ٹیسٹنگ کریش یا غلط آؤٹ پٹ کا خطرہ کم کرتی ہے۔ یہ یہ بھی تصدیق کرنے میں مدد دیتی ہے کہ تبدیلیاں موجودہ خصوصیات نہ توڑیں۔ مکمل طور پر ٹیسٹ شدہ ایپلی کیشنز زیادہ قابل اعتماد اور مستحکم ہوتی ہیں۔

پروگرامنگ کی غلطیوں اور بگز کی عام اقسام: سنٹیکس غلطیاں تب ہوتی ہیں جب کوڈ زبان کے قواعد پر عمل نہ کرے — مثلاً کولن غائب: if x > 5 (بغیر کولن) → SyntaxError: invalid syntax؛ پروگرام چل نہیں پاتا کیونکہ پائتھون سنٹیکس غلط ہے۔ درست: if x > 5: print("x is greater")۔ لاجک غلطیاں تب ہوتی ہیں جب پروگرام غلط نتائج دے — مثلاً length = 5، width = 3، area = length + width سے 8 ملتا ہے (غلط)؛ درست لاجک area = length × width سے 15 ملتا ہے۔ پروگرام چلتا ہے لیکن نتیجہ غلط ہے کیونکہ فارمولا غلط ہے۔ رن ٹائم غلطیاں پروگرام چلتے وقت ظاہر ہوتی ہیں — مثلاً a = 10، b = 0، result = a / b → ZeroDivisionError: division by zero؛ پروگرام عمل کے دوران رک جاتا ہے کیونکہ غلط آپریشن ہوتا ہے۔ دیگر عام بگز میں ڈیٹا غلطیاں اور ریسورس لیکس شامل ہیں۔ ان غلطیوں کی شناخت مستحکم ایپلی کیشنز بنانے کی کلید ہے۔

Syntax ErrorProgram fails to runMissing colon Logic ErrorRuns, wrong result5 + 3 instead of 5 × 3 Runtime ErrorStops while runningDivision by zero
Errors samjho: تین غلطیاں یاد رکھو — syntax کبھی چلتا ہی نہیں, logic چلتا ہے مگر غلط جواب دیتا ہے, runtime چلتے چلتے crash کرتا ہے.
Three error types: syntax (never runs), logic (runs, wrong answer), runtime (crashes while running).
غلطیوں کی تین اقسام: سنٹیکس (کبھی نہیں چلتا)، لاجک (چلتا ہے، غلط جواب)، رن ٹائم (چلتے وقت کریش)۔
2. ✅ Unit Testing — unittest and pytestیونٹ ٹیسٹنگ — unittest اور pytest
🏷 Tags: Unit, Testing, Unittest, Pytest
ENGLISH

Unit testing is the process of testing individual parts or units of a program to ensure they work correctly. It helps catch errors early and makes debugging easier. Python provides modules like unittest and pytest for writing and running tests. These modules allow automated testing of functions and methods. Unit tests check whether each component produces the expected output. Writing clear and simple test cases improves code reliability.

Introduction to Python's unittest and pytest modules: the unittest module is built into Python and provides a framework for creating test cases. Pytest is an external module that simplifies writing and running tests. Both modules help verify that code behaves as expected. They can test individual functions, classes, or entire modules. Using these tools improves program stability and reduces errors in larger applications.

Writing and executing test cases: test cases define specific inputs and the expected output for a function. For example, a calculator function can be tested for addition and subtraction results. Python executes these tests and reports failures or errors. Repeated testing ensures that changes in code do not break existing functionality. Automated test execution saves time and improves accuracy in development.

# Function to test
# This function takes two input values, a and b.
# It returns the sum of both values.
def add(a, b):
    return a + b

# This function takes two input values, a and b.
# It returns the product of both values.
def multiply(a, b):
    return a * b

# Using pytest to test functions
# In pytest, every test function usually starts with the word "test_".
# Pytest automatically detects and runs these test functions.

def test_add():
    # This test checks whether the add() function gives the correct result.
    # Here, 2 and 3 are passed as input values.
    # The expected output is 5.
    assert add(2, 3) == 5  # Test passes because 2 + 3 = 5

def test_multiply():
    # This test checks whether the multiply() function gives the correct result.
    # Here, 2 and 3 are passed as input values.
    # The expected output is 6.
    assert multiply(2, 3) == 6  # Test passes because 2 * 3 = 6

Why pytest is simpler: pytest simplifies testing. It does not require test case classes or boilerplate code like unittest. The tests are written as simple functions, and assert is used to check if the output is correct. To run the tests, simply execute pytest in the command line in the directory where the file is located.

اردو

یونٹ ٹیسٹنگ پروگرام کے انفرادی حصوں یا یونٹس کو جانچنے کا عمل ہے تاکہ یقینی ہو کہ وہ درست کام کرتے ہیں۔ یہ غلطیاں جلدی پکڑنے میں مدد دیتی ہے اور ڈی بگنگ آسان بناتی ہے۔ پائتھون ٹیسٹس لکھنے اور چلانے کے لیے unittest اور pytest جیسے ماڈیولز دیتا ہے۔ یہ ماڈیولز فنکشنز اور میتھڈز کی خودکار ٹیسٹنگ کی اجازت دیتے ہیں۔ یونٹ ٹیسٹس چیک کرتے ہیں کہ آیا ہر جزو متوقع آؤٹ پٹ دیتا ہے۔ واضح اور سادہ ٹیسٹ کیسز لکھنا کوڈ کی قابل اعتمادیت بہتر کرتا ہے۔

پائتھون کے unittest اور pytest ماڈیولز کا تعارف: unittest ماڈیول پائتھون میں بلٹ ان ہے اور ٹیسٹ کیسز بنانے کے لیے فریم ورک دیتا ہے۔ Pytest ایک بیرونی ماڈیول ہے جو ٹیسٹس لکھنا اور چلانا آسان بناتا ہے۔ دونوں ماڈیولز یہ تصدیق کرنے میں مدد دیتے ہیں کہ کوڈ توقع کے مطابق برتاؤ کرتا ہے۔ یہ انفرادی فنکشنز، کلاسز یا مکمل ماڈیولز ٹیسٹ کر سکتے ہیں۔ ان ٹولز کا استعمال پروگرام کی استحکام بہتر کرتا ہے اور بڑی ایپلی کیشنز میں غلطیاں کم کرتا ہے۔

ٹیسٹ کیسز لکھنا اور چلانا: ٹیسٹ کیسز کسی فنکشن کے لیے مخصوص ان پٹس اور متوقع آؤٹ پٹ طے کرتے ہیں۔ مثلاً کیلکولیٹر فنکشن کو جمع اور تفریق کے نتائج کے لیے ٹیسٹ کیا جا سکتا ہے۔ پائتھون یہ ٹیسٹس چلاتا ہے اور ناکامیوں یا غلطیوں کی رپورٹ دیتا ہے۔ بار بار ٹیسٹنگ یقینی بناتی ہے کہ کوڈ میں تبدیلیاں موجودہ فعالیت نہ توڑیں۔ خودکار ٹیسٹ عمل وقت بچاتا ہے اور ڈویلپمنٹ میں درستگی بہتر کرتا ہے۔

# ٹیسٹ کرنے والا فنکشن
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

# pytest سے ٹیسٹ
def test_add():
    assert add(2, 3) == 5  # ٹیسٹ پاس: 2 + 3 = 5

def test_multiply():
    assert multiply(2, 3) == 6  # ٹیسٹ پاس: 2 * 3 = 6

pytest کیوں آسان ہے: pytest ٹیسٹنگ آسان بناتا ہے۔ اسے unittest کی طرح ٹیسٹ کیس کلاسز یا بوائلرپلیٹ کوڈ کی ضرورت نہیں۔ ٹیسٹس سادہ فنکشنز کے طور پر لکھے جاتے ہیں، اور آؤٹ پٹ درست ہے یا نہیں یہ چیک کرنے کے لیے assert استعمال ہوتا ہے۔ ٹیسٹس چلانے کے لیے بس اس ڈائریکٹری میں کمانڈ لائن میں pytest چلائیں جہاں فائل موجود ہے۔

Test case: inputs assert == expected Pass / Fail report
Unit test samjho: unit test چھوٹے حصے کو الگ سے check کرتا ہے — input دو, expected output سے ملاؤ, pass یا fail کی report لو.
Unit test flow: specific inputs → assert against expected output → pass/fail report.
یونٹ ٹیسٹ کا بہاؤ: مخصوص ان پٹس → متوقع آؤٹ پٹ سے assert → پاس/فیل رپورٹ۔
3. 🔍 Using Breakpoints and Watches — Step-by-Step Debuggingبریک پوائنٹس اور واچز — مرحلہ وار ڈی بگنگ
🏷 Tags: Breakpoints, Watches, Step, Debugging
ENGLISH

Breakpoints and watches are tools used in debugging to analyze program behavior. They allow pausing program execution and examining data at specific points. These tools help identify errors and understand how code flows. Using breakpoints and watches makes debugging faster and more precise.

Setting breakpoints in IDEs like PyCharm or VS Code: breakpoints are markers that pause program execution at a chosen line of code. IDEs like PyCharm and VS Code allow setting breakpoints with a simple click. When the program reaches a breakpoint, execution stops, and the current state can be examined. Breakpoints help focus on specific sections of code without running the entire program.

Monitoring variable values with watch expressions: watch expressions track the values of variables while the program is running. They update automatically when variable values change. This helps identify incorrect or unexpected data during execution. Watches allow observing how data changes step by step in real time.

Step-by-step debugging process: step-by-step debugging executes code one line or function at a time. It helps follow the program's logic and detect where errors occur. Developers can step into functions, step over lines, or continue execution after a breakpoint. This process makes it easier to locate and fix bugs accurately.

def calculate_area(radius):
    # Set a breakpoint here to pause and check the value of 'radius'
    area = 3.14 * radius ** 2
    return area

def main():
    # Step-by-step debugging: starting from here
    radius = 5
    print("Area of circle:", calculate_area(radius))  # Set another breakpoint here to monitor return value

    radius = 10  # Change the radius value
    print("Area of circle:", calculate_area(radius))

# Start the program
if __name__ == "__main__":
    main()

Notes: the function calculate_area(radius) calculates the area of a circle using the formula 3.14 * radius ** 2 and returns the calculated value. The main() function tests the area calculation twice by using two different radius values: 5 and 10. Breakpoints can be placed inside calculate_area() and near the print() statements to check the value of radius, observe the calculated area, and understand step-by-step debugging.

1. Setting Breakpoints in IDEs like PyCharm: in PyCharm, you can set breakpoints by clicking the line number next to the code (in the margin). When the program runs and reaches a breakpoint, it pauses. At this point, you can inspect variable values and see the current state of the program. Example: set breakpoints at radius = 5 and radius = 10 to pause the program execution at these lines.
2. Monitoring Variable Values with Watch Expressions: in your IDE, you can use watch expressions to track variables like radius during execution. When you run the debugger, watch expressions will display how the value of radius changes as the program runs. Example: you can add a watch for radius and see its value change from 5 to 10 as the program progresses.
3. Step-by-Step Debugging Process: step-by-step debugging is available in PyCharm. You can choose: Step Into — go inside a function to see how it is working (calculate_area in the example). Step Over — execute the current line and move to the next one without going inside any functions. Continue — continue the execution until the next breakpoint. Example: you can step over the line area = 3.14 * radius ** 2 to skip calculating the area, or step into calculate_area() to examine how the area is calculated.

اردو

بریک پوائنٹس اور واچز ڈی بگنگ میں پروگرام کے رویے کا تجزیہ کرنے کے ٹولز ہیں۔ یہ مخصوص مقامات پر پروگرام کے عمل کو روکنے اور ڈیٹا جانچنے کی اجازت دیتے ہیں۔ یہ ٹولز غلطیاں پہچاننے اور یہ سمجھنے میں مدد دیتے ہیں کہ کوڈ کیسے بہتا ہے۔ بریک پوائنٹس اور واچز استعمال کرنے سے ڈی بگنگ تیز اور زیادہ درست ہو جاتی ہے۔

PyCharm یا VS Code جیسے IDEs میں بریک پوائنٹس سیٹ کرنا: بریک پوائنٹس وہ نشان ہیں جو کوڈ کی منتخب سطر پر پروگرام کا عمل روک دیتے ہیں۔ PyCharm اور VS Code جیسے IDEs ایک سادہ کلک سے بریک پوائنٹس سیٹ کرنے کی اجازت دیتے ہیں۔ جب پروگرام بریک پوائنٹ تک پہنچتا ہے تو عمل رک جاتا ہے، اور موجودہ حالت جانچی جا سکتی ہے۔ بریک پوائنٹس پورا پروگرام چلائے بغیر کوڈ کے مخصوص حصوں پر توجہ دینے میں مدد دیتے ہیں۔

واچ ایکسپریشنز سے متغیرات کی قدریں مانیٹر کرنا: واچ ایکسپریشنز پروگرام چلتے وقت متغیرات کی قدریں ٹریک کرتے ہیں۔ جب متغیرات کی قدریں بدلتی ہیں تو یہ خود بخود اپ ڈیٹ ہوتے ہیں۔ اس سے عمل کے دوران غلط یا غیر متوقع ڈیٹا پہچاننے میں مدد ملتی ہے۔ واچز ڈیٹا کو حقیقی وقت میں مرحلہ وار بدلتے دیکھنے کی اجازت دیتے ہیں۔

مرحلہ وار ڈی بگنگ کا عمل: مرحلہ وار ڈی بگنگ کوڈ کو ایک سطر یا ایک فنکشن کے حساب سے چلاتی ہے۔ یہ پروگرام کی لاجک کی پیروی کرنے اور یہ پتا لگانے میں مدد دیتی ہے کہ غلطیاں کہاں ہوتی ہیں۔ ڈویلپرز فنکشنز میں داخل ہو سکتے ہیں، سطروں کو چھوڑ سکتے ہیں، یا بریک پوائنٹ کے بعد عمل جاری رکھ سکتے ہیں۔ یہ عمل بگز کو درست طور پر ڈھونڈنا اور ٹھیک کرنا آسان بناتا ہے۔

def calculate_area(radius):
    area = 3.14 * radius ** 2
    return area

def main():
    radius = 5
    print("Area of circle:", calculate_area(radius))   # 78.5
    radius = 10
    print("Area of circle:", calculate_area(radius))   # 314.0

if __name__ == "__main__":
    main()

نوٹ: calculate_area(radius) فنکشن 3.14 * radius ** 2 فارمولے سے دائرے کا رقبہ نکالتا ہے اور نکالی گئی قدر واپس دیتا ہے۔ main() فنکشن دو مختلف ریڈیس قدروں 5 اور 10 سے رقبے کی گنتی دو بار جانچتا ہے۔ calculate_area() کے اندر اور print() بیانات کے قریب بریک پوائنٹس لگا کر radius کی قدر چیک کی جا سکتی ہے، نکالا گیا رقبہ دیکھا جا سکتا ہے، اور مرحلہ وار ڈی بگنگ سمجھی جا سکتی ہے۔

1۔ PyCharm جیسے IDEs میں بریک پوائنٹس سیٹ کرنا: PyCharm میں آپ کوڈ کے ساتھ سطر نمبر (مارجن میں) پر کلک کر کے بریک پوائنٹس سیٹ کر سکتے ہیں۔ جب پروگرام چل کر بریک پوائنٹ تک پہنچتا ہے تو یہ رک جاتا ہے۔ اس موقع پر آپ متغیرات کی قدریں جانچ سکتے ہیں اور پروگرام کی موجودہ حالت دیکھ سکتے ہیں۔ مثال: radius = 5 اور radius = 10 پر بریک پوائنٹس سیٹ کریں تاکہ پروگرام ان سطروں پر رکے۔
2۔ واچ ایکسپریشنز سے متغیرات کی قدریں مانیٹر کرنا: اپنے IDE میں آپ عمل کے دوران radius جیسے متغیرات ٹریک کرنے کے لیے واچ ایکسپریشنز استعمال کر سکتے ہیں۔ جب آپ ڈی بگر چلاتے ہیں تو واچ ایکسپریشنز دکھائیں گی کہ پروگرام چلتے وقت radius کی قدر کیسے بدلتی ہے۔ مثال: radius کے لیے واچ شامل کریں اور دیکھیں کہ پروگرام آگے بڑھتے وقت اس کی قدر 5 سے 10 ہو جاتی ہے۔
3۔ مرحلہ وار ڈی بگنگ کا عمل: مرحلہ وار ڈی بگنگ PyCharm میں دستیاب ہے۔ آپ چن سکتے ہیں: Step Into — فنکشن کے اندر جا کر دیکھیں کہ یہ کیسے کام کر رہا ہے (مثال میں calculate_area)۔ Step Over — موجودہ سطر چلا کر اگلی پر جائیں بغیر کسی فنکشن کے اندر جائے۔ Continue — اگلے بریک پوائنٹ تک عمل جاری رکھیں۔ مثال: آپ area = 3.14 * radius ** 2 سطر کو چھوڑ سکتے ہیں، یا calculate_area() میں داخل ہو کر دیکھ سکتے ہیں کہ رقبہ کیسے نکالا جاتا ہے۔

● Breakpoint: pause 👁 Watch: radius 5 → 10 Step Into / Over
Debugging samjho: breakpoint program کو روکتا ہے, watch values پر نظر رکھتا ہے, step line-by-line چلاتا ہے — تینوں مل کر غلطی ڈھونڈتے ہیں.
Debugging tools: breakpoint pauses, watch tracks values, step controls move line by line.
ڈی بگنگ ٹولز: بریک پوائنٹ روکتا ہے، واچ قدریں ٹریک کرتا ہے، اسٹیپ کنٹرول سطر بہ سطر چلاتا ہے۔
4. 🛡️ Exception Handling — Managing Errors Without Crashingایکسیپشن ہینڈلنگ — کریش کے بغیر غلطیاں سنبھالنا
🏷 Tags: Exception, Handling, Managing, Errors, Without, Crashing
ENGLISH

Exception handling is used to manage errors that occur during program execution. It prevents the program from crashing and allows it to respond gracefully to unexpected situations. Proper exception handling improves program reliability and user experience. Python provides built-in tools to catch and handle exceptions efficiently. Tidbit: exception handling helps programs manage unexpected problems without stopping suddenly.

import sqlite3

try:
    # Connect to database
    connection = sqlite3.connect("school.db")
    cursor = connection.cursor()

    # Insert data into table
    cursor.execute("INSERT INTO students (ID, Name, Age) VALUES (?, ?, ?)", (1, "Ali", 20))

    # Save changes (ensures data integrity)
    connection.commit()
    print("Data inserted successfully")

except sqlite3.Error as e:
    # Handle database errors
    print("Error occurred:", e)
    connection.rollback()  # Undo changes if error occurs

finally:
    # Close connection
    if connection:
        connection.close()
        print("Connection closed")

Key points: try-except → handles errors and prevents crashes; commit() → saves correct data (ensures integrity); rollback() → cancels changes if error occurs; finally → safely closes the database.

Handling multiple exception types effectively: a single program may encounter different types of exceptions. Python allows catching multiple exceptions in one try-except block. Each exception type can be handled with a specific response. This approach prevents unexpected crashes and ensures proper error recovery. Handling multiple exceptions improves program stability and control over errors.

اردو

ایکسیپشن ہینڈلنگ پروگرام کے عمل کے دوران ہونے والی غلطیوں کو منظم کرنے کے لیے استعمال ہوتی ہے۔ یہ پروگرام کو کریش ہونے سے روکتی ہے اور اسے غیر متوقع حالات کا شائستگی سے جواب دینے دیتی ہے۔ مناسب ایکسیپشن ہینڈلنگ پروگرام کی قابل اعتمادیت اور صارف کے تجربے کو بہتر بناتی ہے۔ پائتھون ایکسیپشنز پکڑنے اور سنبھالنے کے لیے بلٹ ان ٹولز دیتا ہے۔ دلچسپ بات: ایکسیپشن ہینڈلنگ پروگراموں کو غیر متوقع مسائل اچانک رکے بغیر سنبھالنے میں مدد دیتی ہے۔

import sqlite3

try:
    connection = sqlite3.connect("school.db")
    cursor = connection.cursor()
    cursor.execute("INSERT INTO students (ID, Name, Age) VALUES (?, ?, ?)", (1, "Ali", 20))
    connection.commit()
    print("Data inserted successfully")
except sqlite3.Error as e:
    print("Error occurred:", e)
    connection.rollback()  # غلطی پر تبدیلیاں واپس
finally:
    if connection:
        connection.close()
        print("Connection closed")

اہم نکات: try-except → غلطیاں سنبھالتی ہے اور کریش روکتی ہے؛ commit() → درست ڈیٹا محفوظ کرتا ہے (سالمیتی یقینی بناتا ہے)؛ rollback() → غلطی پر تبدیلیاں منسوخ کرتا ہے؛ finally → ڈیٹا بیس کو محفوظ طریقے سے بند کرتا ہے۔

کئی ایکسیپشن اقسام کو مؤثر طریقے سے سنبھالنا: ایک پروگرام میں مختلف اقسام کی ایکسیپشنز ہو سکتی ہیں۔ پائتھون ایک try-except بلاک میں کئی ایکسیپشنز پکڑنے کی اجازت دیتا ہے۔ ہر ایکسیپشن قسم کا مخصوص جواب دیا جا سکتا ہے۔ یہ طریقہ غیر متوقع کریش روکتا ہے اور مناسب غلطی بازیابی یقینی بناتا ہے۔ کئی ایکسیپشنز سنبھالنا پروگرام کی استحکام اور غلطیوں پر کنٹرول بہتر کرتا ہے۔

try: risky code except: handle error finally: always runs
Exception samjho: try میں risky code, except میں غلطی کا حل, finally میں وہ کام جو ہر حال میں ہونا ہے — program crash نہیں کرتا.
try-except-finally: try runs risky code, except handles the error, finally always closes up.
try-except-finally: try خطرناک کوڈ چلاتا ہے، except غلطی سنبھالتا ہے، finally ہمیشہ بند کرتا ہے۔
5. ⚡ Profiling and Optimization — Finding the Bottleneckپروفائلنگ اور آپٹیمائزیشن — رکاوٹ ڈھونڈنا
🏷 Tags: Profiling, Optimization, Finding, Bottleneck
ENGLISH

Profiling and optimization help improve the speed and efficiency of a program. Profiling measures how much time and resources each part of the code uses. Optimization focuses on making slow or resource-heavy parts faster. These techniques are important for building high-performance applications. Regular profiling ensures that code remains efficient as it grows. Do You Know? Profiling helps identify slow parts of a program so they can be improved for better performance.

Bottleneck example — nested loop: the following code shows a nested loop:

for i in range(10000):
    for j in range(10000):
        # Some repeated task
        pass

In this code, the outer loop runs 10,000 times. For every single iteration of the outer loop, the inner loop also runs 10,000 times. Therefore, the total number of executions becomes: 10000 × 10000 = 100,000,000. This means the inner statement may run one hundred million times, which can make the program very slow. Such a part of the code is called a performance bottleneck. Profiling tools help programmers identify these slow sections so that they can optimise the code and improve program efficiency.

Measuring performance using profiling tools: profiling tools track the execution time and memory usage of different functions in a program. Python provides modules like cProfile and timeit for this purpose. These tools generate reports showing which parts of the code are slow or resource-intensive. Measuring performance helps prioritize areas for optimization. A profiling report highlights bottlenecks — e.g. in the book's report table, process_data (10 calls, cumulative time 2.500) and read_file (1 call, 2.400) are flagged as bottlenecks, while analyze_results (10 calls, 0.100) is not.

Identifying and fixing performance bottlenecks: performance bottlenecks are sections of code that slow down the program. Profiling reports help locate these bottlenecks. Optimization techniques include improving algorithms, reducing unnecessary operations, or using efficient data structures. Fixing bottlenecks improves overall program speed and responsiveness. The performance test cycle is: Benchmark Run → Verifying results → Infrastructure (network, CPU, disks) → Bottleneck → Fixing bottleneck → Profile → Tuning → Refining tunings → Collecting configuration → Collecting component characteristics → Profiling the application (monitoring and profiling tool) → back to Benchmark Run.

import cProfile
import timeit

# Slow code example
def slow_sum(numbers):
    total = 0

    # Adding numbers one by one using a loop
    for num in numbers:
        total = total + num

    return total

# Fast code example
def fast_sum(numbers):
    # Python built-in sum() is faster and optimised
    return sum(numbers)

# Main function
def main():
    numbers = list(range(1, 1000000))

    print("Slow code result:", slow_sum(numbers))
    print("Fast code result:", fast_sum(numbers))

# Profiling the program using cProfile
print("Profiling Report:")
cProfile.run("main()")

# Comparing execution time using timeit
numbers = list(range(1, 1000000))

slow_time = timeit.timeit(lambda: slow_sum(numbers), number=10)
fast_time = timeit.timeit(lambda: fast_sum(numbers), number=10)

print("\nTime Comparison Report:")
print("Slow code time:", slow_time)
print("Fast code time:", fast_time)

Results: cProfile generates a profiling report that shows how much time each function takes during program execution. slow_sum() is slower because it adds numbers manually using a loop. fast_sum() is faster because it uses Python's built-in sum() function, which is already optimised. The function taking more execution time is called the bottleneck. timeit helps compare the execution time of slow and fast code. Output (exact time values may be different on each computer): Profiling Report: Slow code result: 499999500000, Fast code result: 499999500000, 6 function calls in 0.080 seconds — <module> 0.060, slow_sum 0.050, {built-in sum} 0.010, fast_sum 0.010, main 0.080. Time Comparison Report: Slow code time: 0.42, Fast code time: 0.09. Both functions give the same result: 499999500000. slow_sum() takes more time because it uses a manual loop. fast_sum() takes less time because it uses Python's built-in sum() function. Therefore, slow_sum() is the bottleneck in this program.

اردو

پروفائلنگ اور آپٹیمائزیشن پروگرام کی رفتار اور مؤثریت بہتر بنانے میں مدد دیتے ہیں۔ پروفائلنگ ناپتی ہے کہ کوڈ کا ہر حصہ کتنا وقت اور وسائل استعمال کرتا ہے۔ آپٹیمائزیشن سست یا وسائل زیادہ استعمال کرنے والے حصوں کو تیز کرنے پر توجہ دیتی ہے۔ یہ تکنیکیں اعلیٰ کارکردگی کی ایپلی کیشنز بنانے کے لیے اہم ہیں۔ باقاعدہ پروفائلنگ یقینی بناتی ہے کہ کوڈ بڑھتے وقت مؤثر رہے۔ کیا آپ جانتے ہیں؟ پروفائلنگ پروگرام کے سست حصوں کی نشاندہی کرنے میں مدد دیتی ہے تاکہ انہیں بہتر کارکردگی کے لیے بہتر بنایا جا سکے۔

رکاوٹ کی مثال — نیسٹڈ لوپ: درج ذیل کوڈ نیسٹڈ لوپ دکھاتا ہے:

for i in range(10000):
    for j in range(10000):
        # کچھ بار بار ہونے والا کام
        pass

اس کوڈ میں بیرونی لوپ 10,000 بار چلتا ہے۔ بیرونی لوپ کی ہر ایک تکرار کے لیے اندرونی لوپ بھی 10,000 بار چلتا ہے۔ اس لیے کل عمل کی تعداد بنتی ہے: 10000 × 10000 = 100,000,000۔ یعنی اندرونی بیان سو ملین بار چل سکتا ہے، جو پروگرام کو بہت سست بنا سکتا ہے۔ کوڈ کے ایسے حصے کو پرفارمنس باٹل نیک کہا جاتا ہے۔ پروفائلنگ ٹولز پروگرامروں کو ان سست حصوں کی نشاندہی کرنے میں مدد دیتے ہیں تاکہ وہ کوڈ کو بہتر بنا کر پروگرام کی مؤثریت بڑھا سکیں۔

پروفائلنگ ٹولز سے کارکردگی ناپنا: پروفائلنگ ٹولز پروگرام میں مختلف فنکشنز کے عمل کا وقت اور میموری استعمال ٹریک کرتے ہیں۔ پائتھون اس مقصد کے لیے cProfile اور timeit جیسے ماڈیولز دیتا ہے۔ یہ ٹولز رپورٹس بناتے ہیں جو دکھاتی ہیں کہ کوڈ کے کون سے حصے سست یا وسائل زیادہ استعمال کرنے والے ہیں۔ کارکردگی ناپنا آپٹیمائزیشن کے لیے علاقوں کو ترجیح دینے میں مدد دیتا ہے۔ پروفائلنگ رپورٹ رکاوٹوں کو نمایاں کرتی ہے — مثلاً کتاب کی رپورٹ جدول میں process_data (10 کالز، مجموعی وقت 2.500) اور read_file (1 کال، 2.400) کو رکاوٹ قرار دیا گیا ہے، جبکہ analyze_results (10 کالز، 0.100) نہیں۔

پرفارمنس باٹل نیکس کی نشاندہی اور اصلاح: پرفارمنس باٹل نیکس کوڈ کے وہ حصے ہیں جو پروگرام کو سست کرتے ہیں۔ پروفائلنگ رپورٹس ان رکاوٹوں کو ڈھونڈنے میں مدد دیتی ہیں۔ آپٹیمائزیشن تکنیکوں میں الگورتھم بہتر کرنا، غیر ضروری آپریشنز کم کرنا، یا مؤثر ڈیٹا اسٹرکچرز استعمال کرنا شامل ہے۔ رکاوٹیں ٹھیک کرنا پروگرام کی مجموعی رفتار اور ردعمل بہتر کرتا ہے۔ پرفارمنس ٹیسٹ سائیکل ہے: بینچ مارک رن → نتائج کی تصدیق → انفراسٹرکچر (نیٹ ورک، CPU، ڈسکس) → باٹل نیک → باٹل نیک ٹھیک کرنا → پروفائل → ٹیوننگ → ٹیوننگز بہتر کرنا → کنفیگریشن جمع کرنا → جزو خصوصیات جمع کرنا → ایپلی کیشن کی پروفائلنگ (مانیٹرنگ اور پروفائلنگ ٹول) → واپس بینچ مارک رن۔

import cProfile
import timeit

def slow_sum(numbers):
    total = 0
    for num in numbers:
        total = total + num
    return total

def fast_sum(numbers):
    return sum(numbers)  # پائتھون کا بلٹ ان sum() تیز اور بہتر ہے

def main():
    numbers = list(range(1, 1000000))
    print("Slow code result:", slow_sum(numbers))
    print("Fast code result:", fast_sum(numbers))

print("Profiling Report:")
cProfile.run("main()")

numbers = list(range(1, 1000000))
slow_time = timeit.timeit(lambda: slow_sum(numbers), number=10)
fast_time = timeit.timeit(lambda: fast_sum(numbers), number=10)

print("\nTime Comparison Report:")
print("Slow code time:", slow_time)
print("Fast code time:", fast_time)

نتائج: cProfile ایک پروفائلنگ رپورٹ بناتا ہے جو دکھاتی ہے کہ پروگرام کے عمل کے دوران ہر فنکشن کتنا وقت لیتا ہے۔ slow_sum() سست ہے کیونکہ یہ لوپ سے اعداد دستی طور پر جوڑتا ہے۔ fast_sum() تیز ہے کیونکہ یہ پائتھون کا بلٹ ان sum() فنکشن استعمال کرتا ہے جو پہلے سے بہتر ہے۔ زیادہ عمل کا وقت لینے والے فنکشن کو باٹل نیک کہا جاتا ہے۔ timeit سست اور تیز کوڈ کے عمل کے وقت کا موازنہ کرنے میں مدد دیتا ہے۔ آؤٹ پٹ (ہر کمپیوٹر پر وقت کی صحیح قدریں مختلف ہو سکتی ہیں): Profiling Report: Slow code result: 499999500000، Fast code result: 499999500000، 0.080 سیکنڈز میں 6 فنکشن کالز — <module> 0.060، slow_sum 0.050، {built-in sum} 0.010، fast_sum 0.010، main 0.080۔ Time Comparison Report: Slow code time: 0.42، Fast code time: 0.09۔ دونوں فنکشنز ایک ہی نتیجہ دیتے ہیں: 499999500000۔ slow_sum() زیادہ وقت لیتا ہے کیونکہ یہ دستی لوپ استعمال کرتا ہے۔ fast_sum() کم وقت لیتا ہے کیونکہ یہ پائتھون کا بلٹ ان sum() فنکشن استعمال کرتا ہے۔ اس لیے slow_sum() اس پروگرام میں باٹل نیک ہے۔

Bottleneck: slow_sum() — manual loop, 0.42s Optimised: fast_sum() — built-in sum(), 0.09s Same result: 499999500000 — profiling found the slow part, optimisation fixed it.
Profiling samjho: پہلے ناپو کے وقت کہاں ضائع ہو رہا ہے, پھر وہیں ٹھیک کرو — بنا ناپے optimise کرنا اندھیرے میں تیر چلانا ہے.
Profiling → bottleneck → optimisation: same answer, much less time.
پروفائلنگ → رکاوٹ → آپٹیمائزیشن: ایک ہی جواب، بہت کم وقت۔
📝 Official Exercise — Chapter 5سرکاری ایکسرسائز — باب 5

Answer key (from the book): 1–B, 2–D, 3–B, 4–C, 5–B, 6–B, 7–B, 8–B, 9–A, 10–B.

Answer key (from the book): 1–B, 2–D, 3–B, 4–C, 5–B, 6–B, 7–B, 8–B, 9–A, 10–B.

1. Testing is essential for reliable applications because it helps to: (a) Optimise code performance (b) Identify and fix bugs (c) Reduce the program size (d) Make code run faster

Answer: (b) — Testing detects and removes errors before release so applications work correctly under all conditions.

2. Common types of programming errors include: (a) Syntax error (b) Logic error (c) Runtime error (d) All of the above

Answer: (d) — All three are common error types, plus data errors and resource leaks.

3. Unit testing focuses on: (a) Testing the entire application (b) Testing individual components or functions (c) Testing the user interface (d) Testing database connections

Answer: (b) — Unit testing tests individual parts or units of a program.

4. The Python module used for unit testing is: (a) numpy (b) matplotlib (c) unittest (d) os

Answer: (c) — unittest is built into Python; pytest is the external alternative.

5. The main purpose of using testing tools like unittest and pytest: (a) to increase program size (b) to verify code works correctly (c) to design layouts (d) to compile programs

Answer: (b) — They verify that code behaves as expected.

6. Breakpoints in debugging are used to: (a) Run the program faster (b) Pause the program at specific points and inspect its state (c) Skip certain code sections (d) Optimise the code

Answer: (b) — Breakpoints pause execution at a chosen line so the current state can be examined.

7. Watch expressions in debugging are used to: (a) Change variable values (b) Monitor variable values during program execution (c) Pause the program (d) Display output messages

Answer: (b) — Watches track variable values and update automatically as they change.

8. Step-by-step debugging is used to: (a) Run the program faster (b) Execute code one line at a time for easier error identification (c) Increase the program's performance (d) Compile the code

Answer: (b) — Executing one line at a time follows the program's logic and shows where errors occur.

9. The Python keyword pair used for exception handling is: (a) try-except (b) try-finally (c) try-catch (d) handle-throw

Answer: (a) — try-except (with finally for cleanup); Python has no try-catch.

10. Profiling in programming is used to: (a) Improve the user interface design (b) Measure performance and identify bottlenecks (c) Optimise memory usage only (d) Test for security vulnerabilities

Answer: (b) — Profiling measures time and resource use per function and flags bottlenecks.

ملٹی پل چوائس سوالات

جوابی کلید (کتاب سے): 1–B، 2–D، 3–B، 4–C، 5–B، 6–B، 7–B، 8–B، 9–A، 10–B۔

Multiple Choice Questions — Englishکثیر الانتخابی سوالات — انگریزی

1. Testing is essential for reliable applications because it helps to:

Answer: (b) — Testing detects and removes errors before release so applications work correctly under all conditions.

2. Common types of programming errors include:

Answer: (d) — All three are common error types, plus data errors and resource leaks.

3. Unit testing focuses on:

Answer: (b) — Unit testing tests individual parts or units of a program.

4. The Python module used for unit testing is:

Answer: (c) — unittest is built into Python; pytest is the external alternative.

5. The main purpose of using testing tools like unittest and pytest:

Answer: (b) — They verify that code behaves as expected.

6. Breakpoints in debugging are used to:

Answer: (b) — Breakpoints pause execution at a chosen line so the current state can be examined.

7. Watch expressions in debugging are used to:

Answer: (b) — Watches track variable values and update automatically as they change.

8. Step-by-step debugging is used to:

Answer: (b) — Executing one line at a time follows the program's logic and shows where errors occur.

9. The Python keyword pair used for exception handling is:

Answer: (a) — try-except (with finally for cleanup); Python has no try-catch.

10. Profiling in programming is used to:

Answer: (b) — Profiling measures time and resource use per function and flags bottlenecks.
Multiple Choice Questions — Urduکثیر الانتخابی سوالات — اردو

1۔ قابل اعتماد ایپلی کیشنز کے لیے ٹیسٹنگ ضروری ہے کیونکہ یہ مدد دیتی ہے:

جواب: (b) — ٹیسٹنگ ریلیز سے پہلے غلطیاں ڈھونڈ کر ہٹاتی ہے تاکہ ایپلی کیشنز تمام حالات میں درست کام کریں۔

2۔ پروگرامنگ کی غلطیوں کی عام اقسام میں شامل ہیں:

جواب: (d) — تینوں عام غلطی کی اقسام ہیں، علاوہ ڈیٹا غلطیاں اور ریسورس لیکس۔

3۔ یونٹ ٹیسٹنگ توجہ دیتی ہے:

جواب: (b) — یونٹ ٹیسٹنگ پروگرام کے انفرادی حصوں یا یونٹس کو ٹیسٹ کرتی ہے۔

4۔ یونٹ ٹیسٹنگ کے لیے استعمال ہونے والا پائتھون ماڈیول ہے:

جواب: (c) — unittest پائتھون میں بلٹ ان ہے؛ pytest بیرونی متبادل ہے۔

5۔ unittest اور pytest جیسے ٹیسٹنگ ٹولز استعمال کرنے کا بنیادی مقصد:

جواب: (b) — یہ تصدیق کرتے ہیں کہ کوڈ توقع کے مطابق برتاؤ کرتا ہے۔

6۔ ڈی بگنگ میں بریک پوائنٹس استعمال ہوتے ہیں:

جواب: (b) — بریک پوائنٹس منتخب سطر پر عمل روک دیتے ہیں تاکہ موجودہ حالت جانچی جا سکے۔

7۔ ڈی بگنگ میں واچ ایکسپریشنز استعمال ہوتے ہیں:

جواب: (b) — واچز متغیرات کی قدریں ٹریک کرتے ہیں اور تبدیلی پر خود بخود اپ ڈیٹ ہوتے ہیں۔

8۔ مرحلہ وار ڈی بگنگ استعمال ہوتی ہے:

جواب: (b) — ایک سطر کے حساب سے چلانا پروگرام کی لاجک کی پیروی کرتا ہے اور دکھاتا ہے کہ غلطیاں کہاں ہوتی ہیں۔

9۔ ایکسیپشن ہینڈلنگ کے لیے استعمال ہونے والا پائتھون کی ورڈ جوڑا ہے:

جواب: (a) — try-except (صفائی کے لیے finally کے ساتھ)؛ پائتھون میں try-catch نہیں ہے۔

10۔ پروگرامنگ میں پروفائلنگ استعمال ہوتی ہے:

جواب: (b) — پروفائلنگ ہر فنکشن کے وقت اور وسائل کے استعمال کو ناپتی ہے اور رکاوٹوں کو نمایاں کرتی ہے۔
✍️ Short Questions (with answers)مختصر سوالات (جوابات کے ساتھ)

1. Why is testing essential for ensuring reliable applications?

Testing checks whether an application meets its requirements and all functions produce correct results; it detects and removes errors before release, reduces the risk of crashes or incorrect outputs, and verifies that changes do not break existing features — thoroughly tested applications are more trustworthy and stable.

2. What are some common types of programming errors and bugs?

Syntax errors (code does not follow language rules, e.g. missing colon → program fails to run); logic errors (program produces incorrect results, e.g. length + width instead of ×); runtime errors (appear while running, e.g. division by zero → ZeroDivisionError); plus data errors and resource leaks.

3. What is unit testing, and why is it important in programming?

Unit testing tests individual parts or units of a program (functions, methods) to ensure they work correctly. It catches errors early, makes debugging easier, checks each component produces the expected output, and improves code reliability.

4. How do Python's unittest and pytest modules help in unit testing?

unittest is built into Python and provides a framework for creating test cases; pytest is an external module that simplifies writing and running tests (simple test_ functions, assert, no boilerplate classes). Both verify code behaves as expected, can test functions, classes, or entire modules, and improve stability and reduce errors in larger applications.

5. What is the purpose of writing and executing test cases?

Test cases define specific inputs and the expected output for a function (e.g. add(2, 3) == 5, multiply(2, 3) == 6). Python executes them and reports failures or errors; repeated testing ensures changes do not break existing functionality; automated execution saves time and improves accuracy.

6. How do you set breakpoints in IDEs like PyCharm or VS Code?

Click the line number next to the code (in the margin). When the program reaches a breakpoint, execution stops and the current state can be examined; e.g. set breakpoints at radius = 5 and radius = 10 to pause execution at those lines.

7. What is the role of monitoring variable values with watch expressions during debugging?

Watch expressions track variable values while the program runs and update automatically when values change — e.g. a watch on radius shows it change from 5 to 10 as the program progresses — helping identify incorrect or unexpected data in real time, step by step.

8. What is the step-by-step debugging process in IDEs?

Executing code one line or function at a time to follow the program's logic and detect where errors occur: Step Into (go inside a function, e.g. calculate_area), Step Over (execute the current line and move to the next without going inside functions), Continue (run until the next breakpoint).

9. How does exception handling help in managing multiple exception types effectively?

Python allows catching multiple exceptions in one try-except block, each handled with a specific response (e.g. except sqlite3.Error for database errors, with rollback). This prevents unexpected crashes, ensures proper error recovery, and improves program stability and control over errors.

10. What tools can be used for profiling and measuring performance in Python?

cProfile (generates a report of how much time each function takes, e.g. cProfile.run("main()")) and timeit (compares execution times, e.g. slow_sum 0.42 vs fast_sum 0.09). Both help identify bottlenecks and prioritize optimization.

📖 Long Questions (with answers)طویل سوالات (جوابات کے ساتھ)

1. Why is testing essential for reliable applications, and what role does it play in ensuring program stability?

Testing ensures applications work correctly under all conditions: it checks requirements are met, all functions produce correct results, errors are detected and removed before release, and changes do not break existing features. It reduces the risk of crashes or incorrect outputs and prevents unexpected failures during operation. Debugging locates the cause of errors and fixes them efficiently. Together they increase reliability and user confidence; regular testing keeps programs stable as they grow, and thoroughly tested applications are more trustworthy and stable.

2. Discuss the common types of programming errors and bugs that occur during software development.

Syntax errors: code does not follow language rules (missing colon, wrong keywords) — the program fails to run (SyntaxError). Logic errors: the program runs but produces incorrect results because the formula or logic is wrong (area = length + width gives 8 instead of length × width = 15). Runtime errors: appear while running, e.g. division by zero (ZeroDivisionError) stops the program during execution. Other common bugs include data errors and resource leaks. Identifying these errors is key to building stable applications; testing catches them early, and debugging (breakpoints, watches, step-by-step) locates and fixes them.

3. What is unit testing, and how do Python's unittest and pytest modules support effective testing?

Unit testing tests individual parts or units of a program to ensure they work correctly — catching errors early, making debugging easier, and checking each component produces the expected output. unittest is built into Python and provides a framework for creating test cases; pytest is an external module that simplifies writing and running tests with simple test_ functions and assert, no test case classes or boilerplate. Both can test individual functions, classes, or entire modules, verify code behaves as expected, and improve program stability and reduce errors in larger applications.

4. Explain the process of writing and executing test cases using Python's unittest or pytest modules.

Write the functions to test (e.g. add(a, b) returns a + b; multiply(a, b) returns a * b). Write test functions starting with test_ that define specific inputs and expected outputs: test_add() asserts add(2, 3) == 5 (passes because 2 + 3 = 5); test_multiply() asserts multiply(2, 3) == 6 (passes because 2 * 3 = 6). Pytest automatically detects and runs these test functions; run pytest in the command line in the file's directory. Python executes the tests and reports failures or errors. Repeated testing ensures changes do not break existing functionality; automated execution saves time and improves accuracy.

5. How do breakpoints and watch expressions help in debugging? Discuss their role in identifying issues in the code.

Breakpoints are markers that pause program execution at a chosen line (set with a click in PyCharm/VS Code), letting the programmer inspect variable values and the current state without running the entire program — e.g. breakpoints at radius = 5 and radius = 10. Watch expressions track variable values while the program runs and update automatically, e.g. watching radius change from 5 to 10, revealing incorrect or unexpected data step by step in real time. Together they make debugging faster and more precise: pausing at the right place and observing how data changes shows exactly where the program's behavior goes wrong.

6. Describe how to set breakpoints in IDEs like PyCharm or VS Code, and explain their significance in the debugging process.

Click the line number next to the code (in the margin) in PyCharm or VS Code. When the program runs and reaches a breakpoint, it pauses; at this point you can inspect variable values and see the current state of the program (e.g. set breakpoints at radius = 5 and radius = 10). Significance: breakpoints focus debugging on specific sections of code without running the entire program, make it easier to locate and fix bugs accurately, and work with Step Into / Step Over / Continue to follow the program's logic step by step.

7. What is step-by-step debugging, and how does it help in identifying and fixing bugs in Python programs?

Step-by-step debugging executes code one line or function at a time, following the program's logic to detect where errors occur. Step Into goes inside a function (e.g. calculate_area) to see how it works; Step Over executes the current line and moves to the next without going inside functions (e.g. skipping area = 3.14 * radius ** 2); Continue runs until the next breakpoint. In the circle-area example, stepping through radius = 5 (area 78.5) and radius = 10 (area 314.0) shows exactly how values flow and where a calculation goes wrong, making bugs easy to locate and fix accurately.

8. How does exception handling work in Python? Explain how to handle multiple exception types effectively to prevent program crashes.

Exception handling manages errors during execution so the program does not crash: risky code goes in try; if an exception occurs, the matching except block handles it (e.g. except sqlite3.Error as e prints "Error occurred:" and calls connection.rollback() to undo changes); finally always runs for cleanup (closing the connection). Multiple exception types can be caught in one try-except block, each with a specific response, preventing unexpected crashes and ensuring proper error recovery. commit() saves correct data (ensures integrity); rollback() cancels changes on error; finally safely closes the database. This improves reliability and user experience.

📌 باب کا خلاصہ اور رہنمائی — اس باب میں کیا ہے؟

This chapter teaches how to make code trustworthy: name the three error types, write unit tests with unittest and pytest, debug with breakpoints and watches, handle exceptions without crashing, and find bottlenecks with profiling. Remember one line for each tool — what it does and when to use it.

یہ باب code کو قابلِ بھروسہ بنانا سکھاتا ہے — تین error types, unittest اور pytest سے unit tests, breakpoints اور watches سے debugging, crash کے بغیر exception handling, اور profiling سے bottleneck ڈھونڈنا. ہر tool کے لیے ایک line یاد رکھو — وہ کیا کرتا ہے اور کب استعمال ہوتا ہے.

Revision guidance: Revise in this order: (1) read each section and say its idea in one sentence, (2) cover the answers and redo all 20 MCQs, (3) write the 10 short answers from memory, then (4) plan — not just read — two long answers. Revisit any section whose figure you cannot explain without looking.

دہرائی کی رہنمائی: اس ترتیب سے revise کرو: (1) ہر section پڑھ کر اسکا idea ایک جملے میں بتاؤ, (2) جواب چھپا کر 20 MCQs دوبارہ حل کرو, (3) 10 short answers ذہن سے لکھو, پھر (4) دو long answers صرف پڑھنا نہیں, ان کا plan بناؤ. جس section کی figure بغیر دیکھے سمجہ نہ سکو, اسے دوبارہ پڑھو.

🎯 مزید MCQs اور Tests کے لیے

Chapter-wise tests, fresh random papers اور instant score کے لیے PunjabTest.com کا میں test section دیکھو:

PunjabTest.com — Tests →

PunjabTest.com — Complete Guide Book • FSc Part 2 Computer Science, Chapter 5 (New Book, Session 2026–27) • English + Urdu

← Chapter 4: Development of Graphical User Interface (GUI)Chapter 6: Data and Analysis →