FSc Part 1 Computer Science Chapter 2 Complete Guide Book — Python Programming

FSc Part 1 Computer Science Chapter 2 — Python Programming
Home > PunjabTest.com > FSc Part 1 > Computer Science — all chapters > Chapter 2: Python Programming

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

  1. 2.1 — Introduction to Python: Programming Basics and Setting Up
  2. 2.2 — Basic Syntax, First Program and Comments
  3. 2.2.1 — Variables, Naming Rules and Data Types
  4. 2.2.1.4–5 — Input/Output and Integer/Float Inputs
  5. 2.3–2.3.1 — Operators and Arithmetic Operators
  6. 2.3.2 — Comparison Operators
  7. 2.3.3 — Assignment Operators
  8. 2.3.4–5 — Logical Operators and Expressions
  9. 2.3.6 — Operator Precedence and BMI
  10. 2.4–2.4.1.1 — Control Structures and the if Statement
  11. 2.4.1.2–3 — if-else and Short-hand if-else
  12. 2.4.1.3 — if-elif-else
  13. 2.4.2–2.4.2.1 — Looping and the while Loop
  14. 2.4.2.2 — the for Loop and range()
  15. 2.5.1 — Functions: Defining, Parameters, Return and Defaults
  16. 2.5.2–3 — Libraries, Modules and Packages
  17. 2.6.1 — Lists
  18. 2.6.2 — Tuples
  19. 2.6.3 — Indexing and Slicing
  20. 2.7 — Modular Programming and the main Function
  21. 2.8 — Object-Oriented Programming: Classes and Objects
  22. 2.9 — Exception Handling and File Handling
  23. 2.10 — Testing and Debugging
  24. 📝 Official Exercise Questions — with Answers
  25. 📌 Chapter Summary & Guidance
2.1 — Introduction to Python Programming: Programming Basics and Setting Up۲.۱ — پائتھون پروگرامنگ کا تعارف: پروگرامنگ کی بنیادیں اور سیٹ اپ
🏷 Tags: Python, programming, instructions, IDE, PATH, python.org, interpreter, execute, output
ENGLISH

Think of a computer as a very obedient but very literal helper. It cannot guess what you mean — it only does exactly what it is told. Computer programming is the job of writing that set of instructions in a language the computer can understand and run. Python is one such language, and beginners love it because its sentences look almost like plain English, so you can spend your energy on the idea instead of fighting complicated punctuation.

Writing a program always follows four plain steps. First you write the code, a set of instructions in Python. Then the code is compiled or interpreted — translated into a form the computer understands (Python uses an interpreter, which reads and runs your code line by line). Next the computer executes it, carrying out each instruction. Finally you get the output: a message on the screen, a calculation, or some action the program performs.

Before you can write anything, you must set up a Python development environment — that is just a fancy way of saying "prepare your computer so it can write, run and debug Python code". You download Python from python.org and install it, then pick an IDE (Integrated Development Environment), an editor that colours your code, points out mistakes and runs programs with one click. One small tip from the book's "Tidbits" box is worth remembering: while installing, tick the box that says "Add Python to PATH". That puts Python on a list your computer checks whenever you type a command, so you can run Python easily from the command line. If installing feels like a hurdle, online services also let you write and run Python in a browser with nothing to install.

اردو

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

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

شروع کرنے سے پہلے ڈیولپمنٹ انوائرنمنٹ تیار کریں، یعنی کمپیوٹر کو پائتھون لکھنے، چلانے اور غلطیاں ڈھونڈنے کے قابل بنائیں۔ python.org سے پائتھون انسٹال کریں اور ایک IDE چنیں جو کوڈ کو رنگ دے، غلطی بتائے اور ایک کلک پر پروگرام چلائے۔ انسٹال کرتے وقت "Add Python to PATH" والا ڈبہ ضرور ٹک کریں تاکہ کمانڈ لائن سے پائتھون آسانی سے چل سکے۔

Student writing first Python program
Setup samjho: پہلے Python install کرو, PATH tick کرو, پھر IDE کھولو — اس کے بعد ہر program صرف لکھنا, چلانا اور نتیجہ دیکھنا ہے.
2.2 — Basic Python Syntax and Structure: Your First Program and Comments۲.۲ — پائتھون کی بنیادی ساخت: پہلا پروگرام اور کمنٹس
🏷 Tags: syntax, print function, comments, single-line comment, multi-line comment, triple quotes
ENGLISH

The book opens with the shortest possible proof that Python is friendly. Here is the whole program:

print("This is my first page")

Run it and the screen shows This is my first page. Nothing else happens, and that is the point. print() is a built-in function — a ready-made tool — whose job is to display whatever you put inside its brackets. The message sits inside double quotation marks because it is text, and Python must be told "treat this as words, not as instructions". Notice there is no full stop at the end of the line, no special word to start the program, and no brackets wrapping everything: that bare simplicity is Python's syntax, the set of rules for how code must be written.

Real programs also carry comments: lines the interpreter completely ignores, written for the human reader. A comment explains why a tricky line exists, so that future-you — or a classmate — can understand the code months later. A single-line comment starts with # and runs to the end of that line. A multi-line comment is written between triple quotes, ''' at the start and ''' at the end, and can stretch over several lines:

# This is a single-line comment
print("K2 is the second-highest mountain in the world")
'''
This is a multi-line comment.
It can span multiple lines.
'''
print("Edhi Foundation is the largest volunteer ambulance network.")

Only the two print lines run; the comments never reach the screen. A good habit: comment the reason, not the obvious — "calculate average marks" helps, while "print the result" next to a print line adds nothing.

اردو

کتاب کا پہلا پروگرام بہت چھوٹا ہے، اور یہی اس کی خوبصورتی ہے:

print والا جملہ چلائیں تو اسکرین پر This is my first page لکھا آتا ہے۔ print() ایک تیار فنکشن ہے جس کا کام بریکٹ کے اندر دی گئی چیز دکھانا ہے۔ پیغام ڈبل کوٹس میں اس لیے ہے کہ پائتھون اسے لفظ سمجھے، حکم نہیں۔ لائن کے آخر میں کوئی فل اسٹاپ نہیں، پروگرام شروع کرنے کا کوئی خاص لفظ نہیں — یہی سادگی پائتھون کی سِنٹیکس یعنی کوڈ لکھنے کے اصول ہیں۔

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

print( ... )function"This is myfirst page"Screen parیہی لفظ
Print samjho: print() ایک ڈبہ ہے — اندر جو لفظ ڈالو, وہی screen پر چھاپ جاتا ہے, اور # والی سطر کبھی نہیں چلتی.
2.2.1 — Variables, Naming Rules and Data Types۲.۲.۱ — ویری ایبلز، نام رکھنے کے اصول اور ڈیٹا کی اقسام
🏷 Tags: variable, storage container, naming rules, case-sensitive, reserved keywords, int, float, str, bool
ENGLISH

A variable is a labelled container in the computer's memory. You put a value inside it, and later you can take the value out, look at it, or replace it with something new. That last part matters: unlike a constant, a variable's value can change while the program runs. In Python you create one simply by writing a name, an equals sign, and a value — no declaration ceremony is needed:

age = 17
print("Age is:", age)   # Output: Age is: 17
age = 18
print("Age is:", age)   # Output: Age is: 18

The first print shows 17; after the second assignment the same box holds 18, so the second print shows 18. The equals sign here does not mean "equal to" as in mathematics — it means "store the right-hand value into the left-hand name".

Names must follow four rules. A name must start with a letter (a–z, A–Z) or an underscore (_). After that it may contain letters, digits (0–9) or underscores. Names are case-sensitive, so age and Age are two completely different boxes. And Python's reserved keywords — words like for, while, if — cannot be used as names, because Python already uses them for its own grammar. The book adds a style tip worth adopting early: use meaningful, lowercase names with underscores between words, like student_name instead of a. A reader should guess what a box holds just by reading its label.

Python sorts values into data types. An integer (int) holds whole numbers, like age = 17. A floating-point number (float) holds decimals, like price = 19.99. A string (str) holds text in quotes, like name = "Ali". A Boolean (bool) holds only True or False, like is_student = True — note the capital T, because Python's True is a keyword, not the English word.

اردو

ویری ایبل کمپیوٹر کی میموری میں ایک نام والا ڈبہ ہے۔ اس میں قدر رکھیں، بعد میں نکالیں، دیکھیں یا بدل دیں — یہی اس کی خاص بات ہے کہ پروگرام چلتے ہوئے اس کی قدر بدل سکتی ہے۔ پائتھون میں اسے بنانا بہت آسان ہے: نام لکھیں، برابر کا نشان، اور قدر — بس۔

برابر کا نشان یہاں ریاضی والی "برابری" نہیں، بلکہ حکم ہے کہ "دائیں طرف کی قدر بائیں والے نام میں محفوظ کر دو"۔ پہلی بار age میں 17 رکھا تو پرنٹ میں 17 آیا، پھر 18 رکھا تو وہی ڈبہ 18 دکھانے لگا۔

ناموں کے چار اصول یاد رکھیں: نام حرف یا انڈر اسکور (_) سے شروع ہو، بعد میں حرف، ہندسے یا انڈر اسکور آ سکتے ہیں، نام کیس سینسٹیو ہوتے ہیں (age اور Age دو الگ ڈبے ہیں)، اور پائتھون کے مخصوص الفاظ جیسے for، while، if نام نہیں بن سکتے۔ اچھی عادت: بامعنی، چھوٹے حروف والے نام رکھیں جیسے student_name، تاکہ نام پڑھ کر ہی اندازہ ہو کہ ڈبے میں کیا ہے۔

قدر کی چار عام اقسام ہیں: int مکمل عدد (17)، float اعشاری عدد (19.99)، str کوٹس میں لفظ ("Ali")، اور bool صرف True یا False۔

age17 → intprice19.99 → floatname"Ali" → stris_studentTrue → boolہر ڈبے پر نام لکھا ہوتا ہے — نام بدلو تو ڈبہ بدل جاتا ہے.age ≠ Age (case-sensitive), اور 1variable غلط نام ہے.
Variable samjho: ہر variable ایک label والا ڈبہ ہے — int پورا عدد, float اعشاریہ, str لفظ, bool صرف True/False رکھتا ہے.
2.2.1.4–2.2.1.5 — Input and Output Operations, and Handling Integer and Float Inputs۲.۲.۱.۴ تا ۲.۲.۱.۵ — ان پٹ اور آؤٹ پٹ، اور عددی ان پٹ لینا
🏷 Tags: input function, print function, int conversion, float conversion, user input, string input
ENGLISH

A program that only talks to itself is a lonely thing. Input and output are how a program talks to the user: input takes data in, output sends information out. For input Python gives you input(). It prints a message on the screen, then waits patiently until the user types something and presses Enter, and whatever was typed is stored in a variable:

name = input("Enter your name: ")
print("Hello, " + name + "!")

If the user types Ali, the second line prints Hello, Ali! Here the + joins two strings together. For output, print() takes one or more arguments and displays them, separated by spaces when you pass several values with commas.

Now the trap every beginner meets: input() always returns text, even when the user types digits. If you write age = input("Enter your age: ") and the user types 17, then age holds the string "17", not the number 17 — and "17" + 1 would be an error, not 18. The fix is to convert immediately, wrapping the input in int() for whole numbers or float() for decimals:

# Integer input
user_age = int(input("Enter your age: "))
print("Your age is:", user_age)
# Float input
user_height = float(input("Enter your height in meters: "))
print("Your height is:", user_height, "meter")

Type 17 for age and 1.68 for height, and you get proper numbers you can actually calculate with. Rule of thumb: whenever a number will be used in maths, convert it at the very moment you take it in — never later, when the mistake is harder to spot.

اردو

پروگرام جو صرف خود سے بات کرے وہ ادھورا ہے۔ ان پٹ سے صارف ڈیٹا دیتا ہے اور آؤٹ پٹ سے پروگرام معلومات دکھاتا ہے۔ ان پٹ کے لیے input() فنکشن ہے: یہ اسکرین پر پیغام دکھا کر انتظار کرتا ہے، صارف جو لکھ کر Enter دبائے وہ ویری ایبل میں محفوظ ہو جاتا ہے۔

یہاں ایک عام غلطی سے بچیں: input() ہمیشہ لفظ (string) دیتا ہے، چاہے صارف ہندسے ہی کیوں نہ لکھے۔ اگر age میں "17" لفظ آ جائے تو اس پر حساب نہیں ہوگا۔ حل یہ ہے کہ لیتے ہی تبدیل کر لیں: مکمل عدد کے لیے int() اور اعشاری عدد کے لیے float() لپیٹ دیں۔ یوں عمر 17 اور قد 1.68 اصلی عدد بن جائیں گے جن پر حساب ممکن ہے۔ اصول یاد رکھیں: عدد جس پر حساب کرنا ہے، اسے ان پٹ لیتے وقت ہی تبدیل کریں۔

User لکھتا ہے17 (keyboard)input() دیتا ہے"17" (string)int() بناتا ہے17 (number)
Input samjho: keyboard سے جو بھی آئے پہلے لفظ ہوتا ہے — int() یا float() اسے اصل number بناتا ہے, تبھی حساب چلے گا.
2.3–2.3.1 — Operators and Expressions: Arithmetic Operators۲.۳ تا ۲.۳.۱ — آپریٹرز اور ایکسپریشنز: حسابی آپریٹرز
🏷 Tags: operator, expression, addition, subtraction, multiplication, division, modulus, floor division, exponentiation
ENGLISH

An operator is a symbol that does something to values — it is the verb of a program. An expression is a combination of values, variables and operators that produces a result, like 3 + 4, which evaluates to 7. Python's arithmetic operators cover everything you met in maths class, plus two you probably did not:

# Define variables
a = 10
b = 3
print(a, "+", b, "=", a + b)    # Output: 10 + 3 = 13
print(a, "*", b, "=", a * b)    # Output: 10 * 3 = 30
print(a, "/", b, "=", a / b)    # Output: 10 / 3 = 3.3333333333333335
print(a, "//", b, "=", a // b)  # Output: 10 // 3 = 3
print(a, "%", b, "=", a % b)    # Output: 10 % 3 = 1
print(a, "**", b, "=", a ** b)  # Output: 10 ** 3 = 1000

Walk through them slowly. + adds, − subtracts, * multiplies. Plain division / always gives a decimal answer, even for a clean-looking division — 10 / 3 is a long decimal, not 3. Floor division // throws away the fractional part and keeps only the whole part, so 10 // 3 is 3. Modulus % keeps only the remainder, so 10 % 3 is 1, because 3 goes into 10 three times (9) and 1 is left over — this is the operator you reach for when checking "even or odd" or "divisible by". Finally exponentiation ** raises to a power: 10 ** 3 means 10 × 10 × 10 = 1000. A small warning: ** is power in Python; the caret ^ means something entirely different, so never write 10^3 expecting 1000.

اردو

آپریٹر وہ علامت ہے جو قدر پر کوئی عمل کرتی ہے، اور ایکسپریشن قدر، ویری ایبل اور آپریٹر کا مجموعہ ہے جس کا کوئی نتیجہ نکلتا ہے، جیسے 3 + 4 کا نتیجہ 7 ہے۔

حسابی آپریٹرز یہ ہیں: + جمع، − تفریق، * ضرب۔ عام تقسیم / ہمیشہ اعشاری جواب دیتی ہے، جیسے 10 / 3 ایک لمبا اعشاریہ ہے۔ // (فلور ڈویژن) صرف مکمل حصہ رکھتا ہے، اس لیے 10 // 3 برابر 3 ہے۔ % (موڈولس) صرف باقی بچا ہوا حصہ دیتا ہے، اس لیے 10 % 3 برابر 1 ہے — یہی آپریٹر "جفت یا طاق" جانچنے میں کام آتا ہے۔ ** طاقت (power) ہے: 10 ** 3 یعنی 10×10×10 برابر 1000۔ خبردار: پائتھون میں ^ طاقت نہیں ہے، اس لیے 10^3 لکھ کر 1000 کی امید نہ رکھیں۔

a = 10, b = 3 کے ساتھ+ → 13  |  * → 30  |  / → 3.333…// → 3 (poora hissa)  |  % → 1 (baqi)** → 1000 (10 × 10 × 10)
Arithmetic samjho: / ہمیشہ اعشاریہ دیتا ہے, // صرف پورا حصہ رکھتا ہے, % صرف باقی بچاتا ہے, اور ** طاقت ہے.
2.3.2 — Comparison Operators: Asking True-or-False Questions۲.۳.۲ — موازنہ آپریٹرز: صحیح یا غلط سوالات
🏷 Tags: comparison, equal to, not equal, greater than, less than, boolean result, True False
ENGLISH

Comparison operators do not calculate a number — they ask a question, and the answer is always a Boolean: True or False. That simple fact makes them the engine of every decision a program takes later in this chapter. With x = 10 and y = 5, the book's example runs through all six:

x, y = 10, 5
print(x, ">", y, "=", x > y)    # Output: 10 > 5 = True
print(x, "<", y, "=", x < y)    # Output: 10 < 5 = False
print(x, "==", y, "=", x == y)  # Output: 10 == 5 = False
print(x, "!=", y, "=", x != y)  # Output: 10 != 5 = True
print(x, ">=", y, "=", x >= y)  # Output: 10 >= 5 = True
print(x, "<=", y, "=", x <= y)  # Output: 10 <= 5 = False

Read each line as a sentence: "Is 10 greater than 5?" Yes — True. "Is 10 less than 5?" No — False. Two operators deserve a second look because beginners mix them up. == (two equals signs) compares two values, while = (one equals sign) stores a value — writing if x = 10: when you meant a comparison is one of the most common early errors, and Python will refuse it. And != means "not equal to": it is True exactly when the two sides differ. The last two combine ideas: >= means "greater than or equal to" (10 >= 5 is True, and 5 >= 5 would also be True), while <= is its mirror image.

اردو

موازنہ آپریٹرز عدد نہیں نکالتے، بلکہ سوال پوچھتے ہیں اور جواب ہمیشہ True یا False ہوتا ہے۔ یہی سچ/جھوٹ آگے ہر فیصلے کی بنیاد بنتا ہے۔

x = 10 اور y = 5 کے ساتھ: 10 > 5 سچ ہے، 10 < 5 غلط ہے، 10 == 5 غلط ہے، 10 != 5 سچ ہے، 10 >= 5 سچ ہے، 10 <= 5 غلط ہے۔

دو آپریٹرز میں فرق ضرور سمجھیں: == (دو برابر) موازنہ کرتا ہے جبکہ = (ایک برابر) قدر محفوظ کرتا ہے۔ موازنہ کی جگہ ایک برابر لکھنا نئے سیکھنے والوں کی عام غلطی ہے۔ != کا مطلب "برابر نہیں" ہے، اور >= کا مطلب "بڑا یا برابر" ہے۔

105>= Trueسوال: کیا 10, 5 سے بڑا ہے? جواب: True (haan)
Comparison samjho: ہر comparison ایک سوال ہے — جواب صرف True یا False, کبھی number نہیں.
2.3.3 — Assignment Operators: Storing and Updating in One Step۲.۳.۳ — اسائنمنٹ آپریٹرز: ایک قدم میں محفوظ کرنا اور اپ ڈیٹ کرنا
🏷 Tags: assignment, compound assignment, +=, -=, *=, /=, %=, **=, update variable
ENGLISH

You already know the plain assignment operator =: it stores the right-hand value into the left-hand variable. Compound assignment operators go one step further — they first do an arithmetic operation using the variable's current value, then store the result back into the same variable. They are shorthand, and shorthand you will see in almost every real program, especially inside loops where a counter keeps growing.

Here is the idea, written so that each line is easy to check. Start with a = 10, b = 5, and run the lines one after another, carrying the new value of a forward each time:

a = 10
b = 5
a += b   # a = a + b = 10 + 5 = 15
a -= b   # a = a - b = 15 - 5 = 10
a *= b   # a = a * b = 10 * 5 = 50
a /= b   # a = a / b = 50 / 5 = 10.0
a %= b   # a = a % b = 10.0 % 5 = 0.0
a **= b  # a = a ** b = 0.0 ** 5 = 0.0
print(a)  # Output: 0.0

Each line reads naturally: a += b means "add b to a and keep the result in a". The same pattern holds for −=, *=, /=, %= and **=. Notice that after /= the value becomes a float (10.0), and everything after that stays float — that is why the final answer is 0.0, not 0.

⚠ Book warning — read this before copying the book's outputs. The book prints a different set of results for this same block (after addition 15, after subtraction 5, after multiplication 50, after division 2.0, after modulus 2, after exponentiation 100000). Those numbers do not come from running the lines straight through one after another: most of them match starting fresh from a = 10 each time (10 − 5 = 5, 10 × 5 = 50, 10 / 5 = 2.0, 10 ** 5 = 100000), while the modulus figure 2 only fits if a is still 2.0 from the division line. In other words, the book's printed outputs mix two different ways of running the code. Trust the step-by-step trace above — run it yourself and you will get 15, 10, 50, 10.0, 0.0, 0.0 — and remember the lesson hidden inside the confusion: in a compound assignment, the variable's current value is always the starting point.

اردو

سادہ اسائنمنٹ = دائیں طرف کی قدر بائیں والے ویری ایبل میں محفوظ کرتا ہے۔ مرکب اسائنمنٹ ایک قدم آگے ہے: پہلے ویری ایبل کی موجودہ قدر پر حساب کرتا ہے، پھر نتیجہ اسی ویری ایبل میں واپس محفوظ کر دیتا ہے۔

مثال: a = 10 اور b = 5 سے شروع کریں۔ a += b کا مطلب ہے a میں b جمع کر کے نتیجہ a میں رکھ دو، یعنی 15۔ پھر a −= b سے 10، پھر a *= b سے 50، پھر a /= b سے 10.0، پھر a %= b سے 0.0، اور آخر میں a **= b سے 0.0 بنتا ہے۔ ہر سطر میں شروعات ویری ایبل کی موجودہ قدر سے ہوتی ہے — یہی سب سے اہم نکتہ ہے۔

⚠ کتاب کے بارے میں تنبیہ: کتاب میں اسی بلاک کے مختلف نتائج چھپے ہیں (تفریق کے بعد 5، تقسیم کے بعد 2.0، طاقت کے بعد 100000)۔ یہ نتائج لگاتار چلانے سے نہیں ملتے، بلکہ زیادہ تر ہر سطر کو a = 10 سے نئے سرے سے چلانے سے ملتے ہیں۔ اوپر دیا گیا مرحلہ وار حساب درست ہے — خود چلا کر دیکھیں تو 15، 10، 50، 10.0، 0.0، 0.0 ہی ملے گا۔

a = 10a += 5 → 15a −= 5 → 10ہر قدم پچھلی قیمت سے شروع ہوتا ہے — اس لیے ترتیب ضروری ہے.a = a + b لکھنے کا چھوٹا طریقہ ہی a += b ہے.
Assignment samjho: a += b کا مطلب "a کی موجودہ قیمت میں b جمع کرو اور واپس a میں رکھ دو" — ترتیب بدلی تو جواب بدل جائے گا.
2.3.4–2.3.5 — Logical Operators and Expressions۲.۳.۴ تا ۲.۳.۵ — منطقی آپریٹرز اور ایکسپریشنز
🏷 Tags: logical operators, and, or, not, expression, parentheses, boolean logic, truth
ENGLISH

Comparison operators ask one question at a time. Logical operators let you combine several questions into one bigger question, and the answer is still just True or False. There are three. and is True only when both sides are True — like needing both a ticket and an ID card to enter. or is True when at least one side is True — like being allowed in with a ticket or a pass. not flips a value: not True is False, and not False is True.

x = True
y = False
logical_and = x and y
print(x, "and", y, "=", logical_and)  # Output: True and False = False
logical_or = x or y
print(x, "or", y, "=", logical_or)    # Output: True or False = True
logical_not = not x
print("not", x, "=", logical_not)     # Output: not True = False

Small note on the book here: the comment printed beside the or line in the book reads "True and False = True", but that wording is a slip — the line is an or, so the correct comment is "True or False = True", as shown above. The result itself, True, is right.

An expression, remember, is any combination of values, variables and operators that produces a result. 3 + 4 is an expression with the result 7. Bigger expressions use parentheses () to force an order, exactly as in maths:

result = (3 + 4) * 2   # result is 14

Without the brackets, 3 + 4 * 2 would be 11, because multiplication is done first. With the brackets, the addition happens first (7), and 7 × 2 = 14. Brackets are not decoration — they change the answer, and the next section explains the full pecking order.

اردو

موازنہ آپریٹر ایک وقت میں ایک سوال پوچھتے ہیں، جبکہ منطقی آپریٹرز کئی سوالوں کو ملا کر ایک بڑا سوال بناتے ہیں، اور جواب پھر بھی صرف True یا False ہوتا ہے۔

and صرف تب True ہوتا ہے جب دونوں طرف سچ ہو — جیسے داخلے کے لیے ٹکٹ اور شناختی کارڈ دونوں چاہییں۔ or تب True ہوتا ہے جب کم از کم ایک طرف سچ ہو — ٹکٹ یا پاس میں سے کوئی ایک کافی ہے۔ not قدر کو الٹ دیتا ہے: not True برابر False ہے۔

کتاب میں or والی سطر کے ساتھ کمنٹ میں غلطی سے "and" لکھا ہے، درست کمنٹ "True or False = True" ہے، نتیجہ خود درست ہے۔

ایکسپریشن قدر، ویری ایبل اور آپریٹر کا مجموعہ ہے جس کا نتیجہ نکلتا ہے، جیسے 3 + 4 کا نتیجہ 7 ہے۔ بڑے ایکسپریشن میں بریکٹ () ترتیب طے کرتے ہیں: (3 + 4) * 2 برابر 14 ہے، جبکہ بریکٹ کے بغیر 3 + 4 * 2 برابر 11 ہوتا کیونکہ ضرب پہلے ہوتی ہے۔

x = True, y = FalseTrue and False = False (dono sach hon to hi True)True or False = True (aik bhi sach to True)not True = False (ulta kar do)
Logic samjho: and کو دونوں سچ چاہیے, اور کو ایک ہی کافی ہے, not صرف الٹا کرتا ہے.
2.3.6 — Operator Precedence: Which Operation Happens First۲.۳.۶ — آپریٹرز کی ترجیح: کون سا عمل پہلے ہوگا
🏷 Tags: precedence, parentheses, exponentiation, multiplication division modulus, addition subtraction, BODMAS, BMI
ENGLISH

When an expression has several operators, Python does not simply work left to right. It follows operator precedence — a fixed pecking order, the same idea as BODMAS in maths. From highest to lowest, the order the book teaches is:

1. Parentheses () — whatever is inside brackets is done first. (3 + 2) * 4 = 20, because 5 × 4 follows the bracket. 2. Exponentiation ** — powers come next; 2 ** 3 = 8. 3. Multiplication *, division / and modulus % — these share a level and are done left to right; 4 * 3 = 12, 10 / 2 = 5.0, 11 % 3 = 2. 4. Addition + and subtraction − — the lowest of the four levels; 5 + 2 = 7, 10 − 4 = 6.

The book's own practice expressions show why this matters. Take 10 + 3 * 2 ** 2 − 5 / 5. First the power: 2 ** 2 = 4. Then multiplication and division, left to right: 3 * 4 = 12 and 5 / 5 = 1.0. That leaves 10 + 12 − 1.0 = 21.0. Now take (10 + 3) * (2 ** (2 − 1)) / 5: brackets first, (10 + 3) = 13 and (2 − 1) = 1, so 2 ** 1 = 2; then 13 * 2 = 26; then 26 / 5 = 5.2. Same digits, different brackets, completely different answers — and the book's advice is exactly right: when in doubt, add brackets to make your intended order obvious.

Class activity — BMI, solved correctly. The book asks for a program that takes weight and height, computes Body Mass Index and shows its classification. ⚠ Book warning: the formula printed in the book reads BMI = weight / height, with no square — that is an error. The correct definition is BMI = weight / (height × height), with weight in kilograms and height in metres. With that correction:

weight = float(input("Enter weight in kg: "))
height = float(input("Enter height in meters: "))
bmi = weight / (height ** 2)
print("Your BMI is:", bmi)
if bmi < 18.5:
    print("Classification: Underweight")
elif bmi < 25:
    print("Classification: Normal")
elif bmi < 30:
    print("Classification: Overweight")
else:
    print("Classification: Obese")

Try weight 70 and height 1.75: height squared is 3.0625, and 70 / 3.0625 = 22.86, which falls in the Normal band. (The classification bands themselves are the standard health bands; the book asks for a classification but does not print the bands, so those ranges are supplied here and labelled as such.) If you had used the book's printed formula instead, you would have got 70 / 1.75 = 40 — a wildly wrong "Obese" for a healthy person, which is exactly why checking a formula matters more than copying it.

اردو

جب ایک ایکسپریشن میں کئی آپریٹر ہوں تو پائتھون بائیں سے دائیں نہیں چلتا، بلکہ ترجیح (precedence) کے مقررہ ترتیب پر چلتا ہے، جیسے ریاضی میں BODMAS ہوتا ہے۔ سب سے پہلے بریکٹ ()، پھر طاقت **، پھر ضرب، تقسیم اور موڈولس، اور سب سے آخر میں جمع اور تفریق۔

مثال: 10 + 3 * 2 ** 2 − 5 / 5 میں پہلے 2 ** 2 = 4، پھر 3 * 4 = 12 اور 5 / 5 = 1.0، تو جواب 10 + 12 − 1.0 = 21.0 بنتا ہے۔ بریکٹ بدل دیں تو جواب بدل جاتا ہے، اس لیے شک ہو تو بریکٹ لگا کر اپنی ترتیب واضح کر دیں۔

کلاس سرگرمی — BMI، درست فارمولے کے ساتھ: ⚠ کتاب میں چھپا فارمولا BMI = وزن / قد ہے جس میں مربع نہیں — یہ غلطی ہے۔ درست فارمولا BMI = وزن / (قد × قد) ہے، وزن کلوگرام میں اور قد میٹر میں۔ وزن 70 اور قد 1.75 رکھیں تو BMI تقریباً 22.86 بنتا ہے جو Normal درجے میں آتا ہے۔ درجہ بندی کی حدیں معیاری طبی حدیں ہیں جو کتاب میں نہیں چھپی، اس لیے یہاں بتا دی گئی ہیں۔ کتاب والا فارمولا استعمال کرتے تو 40 آتا جو صحت مند شخص کو غلط طور پر Obese بتا دیتا۔

1. Brackets () — sab se pehle2. Power **3. * / % (left to right)4. + − (آخر میں)
Precedence samjho: سیدھی کی طرح سوچو — اوپر والا پہلے, نیچے والا بعد میں; bracket سب سے اوپر ہے.
2.4–2.4.1.1 — Control Structures and the if Statement۲.۴ تا ۲.۴.۱.۱ — کنٹرول اسٹرکچرز اور if اسٹیٹمنٹ
🏷 Tags: control structures, decision making, looping, if statement, condition, indentation, block
ENGLISH

So far every program you have seen runs straight from top to bottom, like a train that never changes track. Real programs need to control the flow: sometimes they must choose between two paths, sometimes they must repeat a job many times. Python gives two families of control structures for this. Decision making picks a path based on a condition, and looping repeats a block of code. This section and the next few cover decisions; loops follow after.

The simplest decision is the if statement: "if this condition is true, run this block of code; otherwise skip it entirely". Its shape is:

if condition:
    # code to run if the condition is true

Two details in that shape are non-negotiable. The line ends with a colon, which is Python's way of saying "a block follows". And the block underneath is indented — pushed in by four spaces — because indentation is how Python knows which lines belong inside the if. Forget the colon or the indent and Python stops with an error. The book's example makes it concrete:

temperature = 35
if temperature > 30:
    print("It is a hot day")

Here 35 > 30 is True, so the message prints. Change temperature to 25 and the condition becomes False — the print line is skipped silently and the program simply carries on. An if statement never explains itself when it skips; if you want a message for the "otherwise" case too, you need if-else, which is next.

اردو

اب تک کے پروگرام اوپر سے نیچے سیدھے چلتے تھے۔ اصل پروگراموں کو بہاؤ پر کنٹرول چاہیے: کبھی دو راستوں میں سے ایک چننا ہوتا ہے، کبھی ایک کام کئی بار دہرانا ہوتا ہے۔ اس کے لیے پائتھون میں دو خاندان ہیں: فیصلہ سازی (decision making) اور لوپنگ (looping)۔

سب سے سادہ فیصلہ if اسٹیٹمنٹ ہے: "اگر شرط سچ ہے تو یہ بلاک چلاؤ، ورنہ اسے چھوڑ دو"۔ اس کی شکل میں دو باتیں لازمی ہیں: سطر کے آخر میں کولن (:) اور نیچے والا بلاک انڈینٹ یعنی چار اسپیس اندر۔ انڈینٹ ہی بتاتا ہے کہ کون سی سطریں if کے اندر ہیں۔

مثال: temperature = 35 ہو تو 35 > 30 سچ ہے، اس لیے "It is a hot day" چھپے گا۔ temperature = 25 کر دیں تو شرط غلط ہو جائے گی اور پرنٹ والی سطر خاموشی سے چھوٹ جائے گی۔

temperature > 30?TruePrint "It is a hot day"FalseFalse ہو تو block چھوت جاتا ہے — کوئی غلطی نہیں, صرف skip.
If samjho: if ایک مور ہے — شرط سچ ہو تو سیدھا راستہ (block) چلتا ہے, جھوٹ ہو تو راستہ چھوت جاتا ہے.
2.4.1.2–2.4.1.3 — if-else and the Short-hand if-else۲.۴.۱.۲ تا ۲.۴.۱.۳ — if-else اور مختصر if-else
🏷 Tags: if-else, shorthand if-else, ternary, either or, two paths, even odd
ENGLISH

An if on its own handles the "yes" case and stays silent otherwise. Very often you want the "no" case to do something too. That is the if-else statement: one block runs if the condition is true, and a different block runs if it is false. Exactly one of the two blocks runs, never both, never neither:

temperature = 15
if temperature > 30:
    print("It's a hot day")
else:
    print("It's not a hot day")

Since 15 > 30 is False, the else block runs and you get It's not a hot day. Notice the shape again: else: sits at the same indentation as the if, with its own colon and its own indented block. If you indent the else by mistake, Python no longer recognises it as the partner of that if.

When both blocks are just one short action each, Python lets you squeeze the whole decision onto a single line — the short-hand if-else, sometimes called a ternary expression:

temperature = 15
m = "It's a hot day" if (temperature > 30) else "It's not a hot day"
print(m)  # Output: It's not a hot day

Read it in English order: "take the first value if the condition holds, else take the second". The result is stored in m and printed. Short-hand is neat for simple choices, but it turns unreadable the moment the actions get long — then the full if-else block is the kinder choice for whoever reads your code next.

Class activity — even or odd, both ways. The book asks for an if-else and a short-hand version that check whether a number is even or odd. A number is even when dividing it by 2 leaves no remainder, which is exactly what % 2 == 0 tests:

# Full if-else version
number = int(input("Enter a number: "))
if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")
# Short-hand version
message = "Even number" if (number % 2 == 0) else "Odd number"
print(message)

Enter 8 and both versions say Even; enter 7 and both say Odd. Same logic, two shapes — pick the shape that reads most clearly for the job.

اردو

صرف if "ہاں" والی صورت سنبھالتا ہے اور "نہیں" پر خاموش رہتا ہے۔ جب "نہیں" کی صورت میں بھی کچھ کرنا ہو تو if-else استعمال ہوتا ہے: شرط سچ ہو تو پہلا بلاک، غلط ہو تو دوسرا بلاک — دونوں میں سے صرف ایک ہی چلے گا، کبھی دونوں نہیں، کبھی کوئی نہیں۔

مثال میں temperature = 15 ہے، اس لیے 15 > 30 غلط ہے اور else والا بلاک چلے گا: "It's not a hot day"۔ else بھی اسی انڈینٹ پر آتا ہے جس پر if تھا، اور اس کا اپنا کولن اور اپنا بلاک ہوتا ہے۔

جب دونوں بلاک صرف ایک ایک چھوٹا عمل ہوں تو پوری شرط ایک سطر میں لکھی جا سکتی ہے — مختصر if-else: پہلی قدر اگر شرط سچ ہو، ورنہ دوسری قدر۔ یہ چھوٹے فیصلوں کے لیے اچھا ہے، لمبے کاموں کے لیے مکمل if-else زیادہ صاف رہتا ہے۔

کلاس سرگرمی — جفت یا طاق: عدد جفت ہے اگر 2 پر تقسیم سے باقی صفر بچے، یعنی number % 2 == 0۔ 8 ڈالیں تو دونوں طریقے Even بتائیں گے، 7 ڈالیں تو Odd۔

temperature > 30?True → "hot day"False → "not a hot day"
If-else samjho: دو راستے, ایک ہی چلتا ہے — شرط فیصلہ کرتی ہے کہ کون سا.
2.4.1.3 — if-elif-else: Checking Conditions One After Another۲.۴.۱.۳ — if-elif-else: شرطوں کو ایک کے بعد ایک جانچنا
🏷 Tags: elif, multiple conditions, ladder, weather example, positive negative zero
ENGLISH

Life rarely offers just two options, and neither does programming. When you need to check several conditions in order, you use the if-elif-else statement — a ladder of checks where Python walks down the rungs and stops at the first one that is true. (A small bookkeeping note: the book numbers both the short-hand if-else and this statement "2.4.1.3"; that repeated number is a printing slip, and the ladder itself is what matters.)

weather = "cloudy"
if weather == "sunny":
    print("Wear sunglasses")
elif weather == "rainy":
    print("Take an umbrella")
else:
    print("Enjoy your day!")

Follow the ladder with weather = "cloudy". The first check, "cloudy" == "sunny", is False, so Python steps down. The second, "cloudy" == "rainy", is also False, so it steps down again. With no condition left true, the else at the bottom catches everything else and prints Enjoy your day! Change weather to "rainy" and the ladder stops at the second rung — the else is never reached. Two rules govern the ladder: only the first true block runs, even if a later condition would also be true, and the final else is optional but useful as a safety net for "anything else".

Class activity — positive, negative or zero. The book asks for exactly this ladder applied to a number:

number = int(input("Enter a number: "))
if number > 0:
    print("Positive number")
elif number < 0:
    print("Negative number")
else:
    print("Zero")

Enter 5 and you get Positive; −3 gives Negative; 0 falls through both checks into the else and gives Zero. Note the order matters here too: had the first check been "number != 0", zero's case would never have been reached cleanly — always put the most specific checks first.

اردو

زندگی میں اکثر صرف دو آپشن نہیں ہوتے، پروگرامنگ میں بھی نہیں۔ جب کئی شرطیں ترتیب سے جانچنی ہوں تو if-elif-else استعمال ہوتا ہے — یہ ایک سیڑھی ہے جس پر پائتھون اوپر سے نیچے چلتا ہے اور پہلی سچی شرط پر رک جاتا ہے۔ (کتاب میں اس کا نمبر بھی 2.4.1.3 چھپا ہے جو مختصر if-else کا بھی نمبر ہے — یہ چھپائی کی غلطی ہے، سیڑھی کا تصور اصل بات ہے۔)

مثال: weather = "cloudy" ہو تو پہلی شرط غلط، دوسری بھی غلط، تو آخر والا else چلے گا: "Enjoy your day!"۔ weather = "rainy" کر دیں تو سیڑھی دوسرے زینے پر رک جائے گی اور else تک پہنچے گی ہی نہیں۔ اصول: صرف پہلا سچا بلاک چلتا ہے، اور آخری else اختیاری مگر "باقی سب" کے لیے حفاظتی جال ہے۔

کلاس سرگرمی — مثبت، منفی یا صفر: عدد 0 سے بڑا ہو تو Positive، 0 سے چھوٹا ہو تو Negative، ورنہ else سے Zero۔ ترتیب اہم ہے — مخصوص شرطیں پہلے رکھیں۔

sunny? → sunglassesrainy? → umbrellaelse → Enjoy your day!پہلی sachi سیدھی پر رک جاؤ — نیچے کی سیڑھیاں پھر نہیں دیکھی jatin.
Elif samjho: seedhi neechay utro, pehli sachi shart miltay hi ruk jao, baqi sab chhor do.
2.4.2–2.4.2.1 — Looping Constructs: the while Loop۲.۴.۲ تا ۲.۴.۲.۱ — لوپنگ: while لوپ
🏷 Tags: while loop, looping, iteration, condition checked first, counter, infinite loop
ENGLISH

Loops exist so you never have to write the same instruction twenty times. A while loop repeats a block as long as a condition stays true, checking that condition before every single repetition — including the first one, which means the block might run zero times if the condition is already false. The book's example adds 1 to a number until it reaches 10:

number = 1
while number < 10:
    print(number)
    number += 1

Trace it like a careful accountant. number starts at 1: 1 < 10 is True, so print 1, then number becomes 2. 2 < 10 is True, print 2, become 3. This continues — 3, 4, 5, 6, 7, 8, 9 — until number becomes 10. Now 10 < 10 is False, and the loop stops. Output: 1 2 3 4 5 6 7 8 9, each on its own line. The line number += 1 is the hero of this story: without it, number would stay 1 forever, the condition would never turn false, and you would have an infinite loop — a program that never stops. Every while loop needs something inside it that moves the condition towards false.

Class activity — evens printed, odds counted, 1 to 20. The book asks for a while loop that prints the even numbers from 1 to 20 and counts the odd ones:

number = 1
odd_count = 0
while number <= 20:
    if number % 2 == 0:
        print(number)
    else:
        odd_count += 1
    number += 1
print("Total odd numbers:", odd_count)

The evens printed are 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, and the final line reports Total odd numbers: 10 — because exactly half of 1–20, the numbers 1, 3, 5, …, 19, are odd. Notice the counter pattern: start a counting variable at 0 outside the loop, add 1 inside whenever the thing you are counting happens, and report it after the loop ends.

اردو

لوپ اس لیے ہیں تاکہ ایک ہی ہدایت بیس بار نہ لکھنی پڑے۔ while لوپ بلاک کو اس وقت تک دہراتا ہے جب تک شرط سچ رہے، اور شرط ہر دہراؤ سے پہلے جانچی جاتی ہے — پہلے دہراؤ سے پہلے بھی، اس لیے اگر شرط شروع ہی میں غلط ہو تو بلاک ایک بار بھی نہیں چلے گا۔

مثال: number = 1 سے شروع کریں۔ 1 < 10 سچ ہے تو 1 چھپے گا اور number 2 ہو جائے گا، پھر 2، 3 … 9 تک چھپیں گے، اور جب number 10 ہو جائے گا تو 10 < 10 غلط ہو جائے گا اور لوپ رک جائے گا۔ نتیجہ: 1 سے 9 تک عدد۔

سب سے اہم سطر number += 1 ہے: اس کے بغیر number ہمیشہ 1 رہتا، شرط کبھی غلط نہ ہوتی، اور پروگرام کبھی نہ رکتا — اسے لامحدود لوپ کہتے ہیں۔ ہر while لوپ کے اندر کوئی ایسی چیز ہونی چاہیے جو شرط کو غلط کی طرف لے جائے۔

کلاس سرگرمی — 1 سے 20 تک جفت چھاپیں، طاق گنیں: جفت عدد 2، 4 … 20 چھپیں گے اور آخر میں Total odd numbers: 10 آئے گا، کیونکہ 1 سے 20 میں طاق عدد دس ہیں۔ گننے کا طریقہ: لوپ سے باہر کاؤنٹر صفر سے شروع کریں، اندر ہر بار ایک بڑھائیں، لوپ کے بعد رپورٹ کریں۔

number < 10?Print, phir += 1واپس اوپر — شرط پھر جانچی جاتی ہے.False hotay hi loop khatam, program aagay.
While samjho: چکر ہر بار شرط پوچھتا ہے — سچ ہو تو کام, جھوٹ ہو تو رک جاؤ; counter بڑھانا مت بھولنا.
2.4.2.2 — the for Loop and range()۲.۴.۲.۲ — for لوپ اور range() فنکشن
🏷 Tags: for loop, range function, sequence, iterate, list iteration, step
ENGLISH

While a while loop repeats "until something changes", a for loop repeats "for each item in a collection" — it is the natural choice when you already know what you want to walk through, like a list, a tuple or a string. Its shape is:

for variable in sequence:
    # code to run for each element in the sequence

The book's first example greets every friend in a list:

friends = ["Ahmad", "Ali", "Hassan"]
for friend in friends:
    print("Hello", friend)

On the first round, friend holds "Ahmad" and the screen shows Hello Ahmad. On the second round friend becomes "Ali", then "Hassan". Three items, three rounds, then the loop ends by itself — no counter to update, no condition to remember, and therefore no risk of an infinite loop from a forgotten update. That safety is the for loop's quiet advantage.

But what if you want numbers rather than items from a list? That is what range() is for: it produces a sequence of numbers on demand. range(5) gives 0, 1, 2, 3, 4 (it stops before 5). range(2, 11, 2) starts at 2, steps by 2, and stops before 11, giving 2, 4, 6, 8, 10. Note carefully: range() creates a sequence of numbers for looping — it does not print anything by itself, and it is not a list (a point the book's exercise key gets wrong, as flagged in the exercise below).

Class activities, solved. (1) Even numbers from 2 to 10 with range():

for number in range(2, 11, 2):
    print(number)  # 2, 4, 6, 8, 10

(2) The first 10 multiples of 3 with a for loop and range():

for number in range(3, 31, 3):
    print(number)  # 3, 6, 9, 12, 15, 18, 21, 24, 27, 30

The stop value is 31, not 30, because range() always stops before its end value — the single most common range() mistake, and the one to watch for in your own code.

اردو

while لوپ "جب تک کچھ بدلے" دہراتا ہے، جبکہ for لوپ "مجموعے کی ہر چیز کے لیے" دہراتا ہے — جب آپ کو پہلے سے معلوم ہو کہ کن چیزوں سے گزرنا ہے، جیسے لسٹ یا سٹرنگ، تو for لوپ قدرتی انتخاب ہے۔

مثال: دوستوں کی لسٹ ["Ahmad", "Ali", "Hassan"] ہو تو پہلے دور میں friend میں "Ahmad" آئے گا اور Hello Ahmad چھپے گا، پھر "Ali"، پھر "Hassan"۔ تین چیزیں، تین دور، پھر لوپ خود ختم — نہ کاؤنٹر اپ ڈیٹ کرنا، نہ شرط یاد رکھنا، اس لیے بھولنے سے لامحدود لوپ کا خطرہ بھی نہیں۔

عدد چاہییں تو range() کام آتا ہے: range(5) دیتا ہے 0، 1، 2، 3، 4 (5 سے پہلے رک جاتا ہے)۔ range(2, 11, 2) دیتا ہے 2، 4، 6، 8، 10۔ یاد رکھیں: range() صرف عددوں کی ترتیب بناتا ہے، خود کچھ نہیں چھاپتا اور یہ لسٹ نہیں ہے۔

کلاس سرگرمیاں: 2 سے 10 تک جفت عدد کے لیے range(2, 11, 2)، اور 3 کے پہلے دس اضعاف کے لیے range(3, 31, 3) — آخری عدد 31 اس لیے کہ range() اپنی آخری حد سے پہلے رک جاتا ہے، 30 لکھتے تو 30 چھوٹ جاتا۔

["Ahmad",friend =Hello AhmadPhir friend = "Ali", phir "Hassan" — har cheez ki aik baari.
For samjho: for loop ہر چیز کو ایک ایک کر کے اٹھاتا ہے — variable ہر دفعہ نئی چیز پکڑتا ہے.
2.5.1 — Functions and Modules: Defining, Calling, Parameters, Return Values and Default Parameters۲.۵.۱ — فنکشنز اور ماڈیولز: بنانا، بلانا، پیرامیٹرز، ریٹرن اور ڈیفالٹ قدر
🏷 Tags: function, def, call, invoke, parameter, argument, return value, default parameter, reuse
ENGLISH

A function is a named, reusable block of code: you write a job once, give it a name, and then run that job whenever you like simply by calling the name. Without functions, a program that greets ten people would repeat the greeting code ten times; with a function, you write it once and call it ten times. Functions are defined with the def keyword, a name, parentheses that may hold parameters (the inputs the function expects), a colon, and an indented body:

def greet(name):
    print("Hello", name)
# Function invoking means call the function by name
greet('Ali')  # Output: Hello Ali

Defining a function does nothing by itself — the body only runs when the function is called. In the call, the value you pass ("Ali") is called an argument; inside the function it arrives as the parameter name. Keep the two words straight: parameters are the labelled slots in the definition, arguments are the actual values in the call.

Some functions do not just print — they hand a result back. return sends a value out of the function to whoever called it:

def add(a, b):
    return a + b
print(add(4, 6))   # Output: 10
print(add(20, 5))  # Output: 25

The same code serves both calls with different inputs — that reuse is the whole point, and the book's "Do You Know?" box says exactly this: call a function many times with different arguments and the same code does different jobs. A function can also carry a default parameter: a value used automatically when the caller provides nothing:

def greet(name = "Student"):
    return "Hello" + name + "!"
print(greet())         # Output: Hello,Student!
print(greet("Umer"))   # Output: Hello, Umer!

The first call passes nothing, so name quietly becomes "Student" and you get "Hello,Student!" — note the missing space, because the book's code joins "Hello" directly to the name without a space; adding a space after Hello, as in "Hello " + name, is the tidier version. The second call passes "Umer", which replaces the default, giving "Hello, Umer!" — the space there comes from the argument itself in the book's printout, another small reason to write the space into your own code rather than relying on the caller.

Class activity — maximum of a list. The book asks for a function that takes a list of numbers and returns the maximum value. Writing it by hand (rather than calling Python's built-in max) shows the logic clearly:

def find_max(numbers):
    largest = numbers[0]
    for number in numbers:
        if number > largest:
            largest = number
    return largest
print(find_max([4, 9, 2, 15, 7]))  # Output: 15

Start by assuming the first item is the largest, then compare every item against it, replacing it whenever a bigger one appears. (The function is named find_max here rather than max, so it does not hide Python's own built-in max function — a naming kindness worth copying.)

اردو

فنکشن کوڈ کا نام والا، دوبارہ استعمال ہونے والا بلاک ہے: کام ایک بار لکھیں، نام دیں، پھر جب چاہیں نام لے کر وہی کام چلا لیں۔ بغیر فنکشن کے دس لوگوں کو سلام کرنے کے لیے سلام والا کوڈ دس بار لکھنا پڑتا، فنکشن سے ایک بار لکھ کر دس بار بلا لیں۔ فنکشن def سے بنتا ہے، پھر نام، بریکٹ میں پیرامیٹرز (وہ ان پٹ جن کی فنکشن کو توقع ہے)، کولن، اور انڈینٹ شدہ باڈی۔

صرف بنانے سے فنکشن نہیں چلتا — باڈی تبھی چلتی ہے جب فنکشن کو بلایا (call) جائے۔ بلاتے وقت دی گئی قدر آرگومنٹ کہلاتی ہے، اور اندر وہی قدر پیرامیٹر بن جاتی ہے۔ فرق یاد رکھیں: پیرامیٹر تعریف میں خانہ ہے، آرگومنٹ بلانے وقت اصل قدر ہے۔

کچھ فنکشن صرف چھاپتے نہیں، نتیجہ واپس بھی دیتے ہیں: return قدر بلانے والے کو واپس بھیج دیتا ہے، جیسے add(4, 6) کا نتیجہ 10 ہے۔ ڈیفالٹ پیرامیٹر وہ قدر ہے جو خود بخود استعمال ہو جائے اگر بلانے والا کچھ نہ دے — greet() بغیر نام کے "Hello,Student!" دیتا ہے، اور greet("Umer") "Hello, Umer!" دیتا ہے۔

کلاس سرگرمی — لسٹ کا سب سے بڑا عدد: پہلا عدد سب سے بڑا فرض کریں، پھر ہر عدد سے موازنہ کریں، بڑا ملے تو بدل دیں۔ آخر میں سب سے بڑا عدد واپس مل جائے گا، جیسے [4, 9, 2, 15, 7] کا جواب 15 ہے۔

greet('Ali')def greet(name):print("Hello", name)Hello AliDefine aik dafa, call jitni dafa chaho — har dafa naya argument.
Function samjho: def سے ایک machine بنتی ہے, call سے وہ چلتی ہے — argument اندر جاتا ہے, کام باہر آتا ہے.
2.5.2–2.5.3 — Using Libraries and Modules, and Package Structure۲.۵.۲ تا ۲.۵.۳ — لائبریریاں اور ماڈیولز، اور پیکج کی ساخت
🏷 Tags: library, module, import, random, datetime, statistics, package, standard library, third-party
ENGLISH

Python's great strength is that you rarely start from zero. A module is a file of ready-made Python code, and a library is a collection of such modules — toolboxes full of tools other people already built and tested, so you can solve a problem without building everything from scratch. Python ships with a huge standard library, and many more third-party libraries can be added later. You bring a module into your program with import, then use its tools with a dot: module name, dot, tool name.

Random numbers come from the random module. random.randint(1, 10) picks a whole number between 1 and 10, both ends included — run it twice and you will very likely get two different answers, which is the whole point:

import random
# Generate a random number between 1 and 10
number = random.randint(1, 10)
print("The random number is:", number)

Dates and times come from datetime. datetime.datetime.now() returns the current date and time at the moment it runs:

import datetime
# Get the current date and time
current_time = datetime.datetime.now()
print("Current date and time:", current_time)

Averages come from statistics. Its mean() adds a list of numbers and divides by how many there are:

import statistics
# Calculate the mean of a list of numbers
data = [23, 45, 67, 89, 12, 44, 56]
mean_value = statistics.mean(data)
print("The mean value is:", mean_value)  # Output: 48.0

Check that last one by hand: the numbers add to 336, and 336 ÷ 7 = 48.0 exactly. When your hand calculation and the library agree, you know you used the tool correctly — a habit worth keeping for every library call you ever make.

When a project grows large, related modules are grouped into a package: simply a folder (directory) holding related module files. The book's example imagines an online shop with a package called ecommerce containing products.py, customers.py and orders.py. Inside ecommerce/products.py sits a function:

# In ecommerce/products.py:
def list_products():
    return ["Laptop", "Mobile", "Tablet"]

And in the main script you import that one module out of the package:

# In your main script
from ecommerce import products
available_products = products.list_products()
print(available_products)
# Output: ['Laptop', 'Mobile', 'Tablet']

The book's "Tidbits" box puts it nicely: organising modules into packages is like organising books into sections of a library — it makes finding and maintaining your code far easier as a project grows.

اردو

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

random ماڈیول سے بے ترتیب عدد ملتا ہے: random.randint(1, 10) دونوں سروں سمیت 1 سے 10 تک کوئی عدد چنتا ہے، ہر بار شاید مختلف۔ datetime سے موجودہ تاریخ اور وقت ملتا ہے۔ statistics کے mean() سے اوسط نکلتی ہے: [23, 45, 67, 89, 12, 44, 56] کا مجموعہ 336 ہے اور 336 ÷ 7 = 48.0 ہے — ہاتھ سے حساب اور لائبریری کا جواب مل جائے تو سمجھیں اوزار درست استعمال ہوا۔

بڑے منصوبے میں متعلقہ ماڈیولز کو پیکج میں رکھتے ہیں، یعنی ایک فولڈر میں متعلقہ فائلیں۔ جیسے ecommerce پیکج میں products.py ہو اور اس میں list_products() فنکشن ہو، تو مرکزی اسکرپٹ میں from ecommerce import products لکھ کر اسے استعمال کر لیں۔ کتاب کا موازنہ اچھا ہے: پیکج میں ماڈیول رکھنا ایسا ہے جیسے لائبریری میں کتابیں حصوں میں رکھنا۔

Libraryrandom • datetimestatistics • …importsirf woh moduleجو چاہیےUse کروmodule.tool()
Library samjho: poora dabba mat uthao — import se sirf zaroori auzaar lo, phir dot laga kar chalao.
2.6.1 — Lists: Creating, Accessing, Modifying, Methods and Operations۲.۶.۱ — لسٹس: بنانا، رسائی، تبدیلی، میتھڈز اور آپریشنز
🏷 Tags: list, square brackets, index, append, remove, sort, reverse, slicing, concatenation
ENGLISH

A list is Python's most everyday container: an ordered collection of items, written inside square brackets [ ] with commas between items. Unlike a single variable, a list holds many values at once — numbers, strings, even other lists — and you can change it after creating it. The book starts with favourite fruits:

fruits = ["Mango", "Apple", "Banana"]
print(fruits)  # Output: ['Mango', 'Apple', 'Banana']

To reach one item you use its index — its position number — and Python counts positions from 0, not 1. So fruits[0] is "Mango", fruits[1] is "Apple" (the second item), and fruits[2] is "Banana":

fruits = ["Mango", "Apple", "Banana"]
print(fruits[1])  # Output: Apple

Changing a list is just as direct. Assign to a position to replace that item, and use append() to add an item at the end:

fruits = ["Mango", "Apple", "Banana"]
fruits[0] = "Orange"
fruits.append("Pineapple")
print(fruits)  # Output: ['Orange', 'Apple', 'Banana', 'Pineapple']

Lists also come with built-in methods — tools that belong to the list itself and are called with a dot. append(item) adds to the end. remove(item) takes out the first occurrence of that value. sort() arranges the list in ascending order (alphabetical for words). reverse() flips the order. The book's sorting example shows append and sort working together:

students = ["Ahmed", "Sara", "Ali"]
students.append("Hina")
students.sort()
print(students)  # Output: ['Ahmed', 'Ali', 'Hina', 'Sara']

Finally, lists support two handy operations. Slicing takes a portion: numbers[1:4] takes items at positions 1, 2 and 3 (the end position is not included). Concatenation with + joins two lists into one:

numbers = [1, 2, 3, 4, 5]
slice = numbers[1:4]  # Gets items from index 1 to 3
extra_numbers = [6, 7]
combined = slice + extra_numbers
print(combined)  # Output: [2, 3, 4, 6, 7]

And sorting plus removing, as in the book's second example: sort ["Ahmed", "Sara", "Ali", "Hina"] alphabetically, then remove "Sara", and you are left with ['Ahmed', 'Ali', 'Hina'].

Class activity — favourite books, all five tasks. Start with ["To Kill a Mockingbird", "1984", "The Great Gatsby", "Pride and Prejudice"], then: (1) append "Moby Dick"; (2) replace "1984" with "Brave New World" by assigning to its index (position 1); (3) remove "The Great Gatsby"; (4) merge with ["War and Peace", "Hamlet"] using +; (5) print the result:

books = ["To Kill a Mockingbird", "1984", "The Great Gatsby", "Pride and Prejudice"]
books.append("Moby Dick")
books[1] = "Brave New World"
books.remove("The Great Gatsby")
books = books + ["War and Peace", "Hamlet"]
print(books)
# Output: ['To Kill a Mockingbird', 'Brave New World', 'Pride and Prejudice', 'Moby Dick', 'War and Peace', 'Hamlet']
اردو

لسٹ پائتھون کا سب سے عام ڈبہ ہے: ترتیب والی چیزوں کا مجموعہ، مربع بریکٹ [ ] میں، کاموں کے درمیان۔ ایک ویری ایبل کے برعکس لسٹ بیک وقت کئی قدریں رکھتی ہے — عدد، لفظ، حتیٰ کہ دوسری لسٹیں — اور بنانے کے بعد اسے بدلا بھی جا سکتا ہے۔

کسی ایک چیز تک پہنچنے کے لیے اس کا انڈیکس یعنی مقام نمبر استعمال ہوتا ہے، اور پائتھون گنتی صفر سے شروع کرتا ہے، ایک سے نہیں۔ اس لیے fruits[0] "Mango" ہے، fruits[1] دوسری چیز "Apple" ہے، اور fruits[2] "Banana" ہے۔

لسٹ بدلنا بھی سیدھا ہے: مقام پر نئی قدر رکھ کر چیز بدلیں، اور append() سے آخر میں چیز شامل کریں۔ لسٹ کے اپنے میتھڈز بھی ہیں جو نقطے سے بلائے جاتے ہیں: append آخر میں جوڑتا ہے، remove پہلی موجودگی نکالتا ہے، sort() ترتیب سے لگاتا ہے، reverse() الٹ دیتا ہے۔

دو کارآمد آپریشنز بھی ہیں: سلائسنگ سے حصہ لیا جاتا ہے — numbers[1:4] مقام 1، 2، 3 کی چیزیں دیتا ہے (آخری مقام شامل نہیں ہوتا) — اور + سے دو لسٹیں جوڑی جاتی ہیں۔

کلاس سرگرمی — پسندیدہ کتابیں: شروع میں چار کتابیں، پھر "Moby Dick" شامل کریں، مقام 1 پر "1984" کی جگہ "Brave New World" رکھیں، "The Great Gatsby" نکالیں، ["War and Peace", "Hamlet"] سے جوڑیں، اور آخری لسٹ چھاپیں — نتیجہ اوپر والے کوڈ میں دیا گیا ہے۔

index 0Mangoindex 1Appleindex 2Bananaappend →Pineappleگنتی 0 سے شروع — اس لیے دوسری چیز کا index 1 ہے, 2 نہیں.
List samjho: list ایک ڈبوں کی قطار ہے — ہر ڈبے پر number (index) لکھا ہے اور گنتی 0 سے شروع ہوتی ہے.
2.6.2 — Tuples: Ordered Collections You Cannot Change۲.۶.۲ — ٹیوپلز: ترتیب والی مجموعے جنہیں بدلا نہیں جا سکتا
🏷 Tags: tuple, immutable, round brackets, ordered collection, len function, index access
ENGLISH

A tuple looks like a list's close cousin: it stores an ordered collection of items, and you read items from it by index exactly as with a list. The difference — and it is the whole reason tuples exist — is that a tuple is immutable, meaning its values cannot be changed after creation. No replacing an item, no appending, no removing. That sounds like a limitation, but it is actually a promise: when a tuple is passed around a program, nobody can accidentally rewrite it, so it is the right container for data that must stay fixed, like the days of the week or the coordinates of a point.

Tuples are written in round brackets ( ) instead of square ones:

# Creating a tuple
my_tuple = (1, 2, 3, "Hello", 4.5)
# Accessing elements by index
print(my_tuple[0])  # Output: 1
print(my_tuple[3])  # Output: Hello
# Tuple length
print(len(my_tuple))  # Output: 5

Indexing works from 0 as usual: my_tuple[0] is the first item, 1, and my_tuple[3] is the fourth item, "Hello". len() counts the items and reports 5 — there are five values inside, even though they mix numbers and text, which is perfectly fine. Try my_tuple[0] = 99 and Python will stop you with an error, and that error is the point: the tuple refused to change, exactly as designed. So the rule of thumb is simple — if the collection should grow or change, use a list; if it must stay exactly as it was made, use a tuple.

اردو

ٹیوپل لسٹ کا قریبی رشتہ دار لگتا ہے: یہ بھی ترتیب والی چیزوں کا مجموعہ رکھتا ہے اور انڈیکس سے چیزیں اسی طرح پڑھی جاتی ہیں۔ فرق — اور یہی اس کے وجود کی وجہ ہے — یہ ہے کہ ٹیوپل ناقابلِ تبدیل (immutable) ہے، یعنی بننے کے بعد اس کی قدریں بدلی نہیں جا سکتیں۔ نہ چیز بدلی جا سکتی ہے، نہ شامل، نہ نکالی جا سکتی ہے۔

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

ٹیوپل گول بریکٹ ( ) میں لکھا جاتا ہے۔ مثال میں my_tuple کے پانچ ارکان ہیں: my_tuple[0] برابر 1، my_tuple[3] برابر "Hello"، اور len(my_tuple) برابر 5 ہے۔ my_tuple[0] = 99 لکھیں تو پائتھون غلطی دے گا — اور یہی غلطی ثابت کرتی ہے کہ ٹیوپل نے بدلنے سے انکار کر دیا، جیسا اسے کرنا چاہیے تھا۔ اصول سادہ ہے: مجموعہ بڑھنا یا بدلنا ہو تو لسٹ، ہمیشہ ایک سا رہنا ہو تو ٹیوپل۔

List [ ]بدل سکتی ہے ✓append, remove, sortTuple ( )نہیں بدل سکتی ✗Sirf parh sakte ho
Tuple samjho: list کھلا register ہے, tuple بند لفافہ ہے — اندر دیکھ سکتے ہو, بدل نہیں سکتے.
2.6.3 — Indexing and Slicing, Including Negative Indices۲.۶.۳ — انڈیکسنگ اور سلائسنگ، بشمول منفی انڈیکس
🏷 Tags: indexing, slicing, negative index, start stop step, sequence, list tuple string
ENGLISH

Indexing and slicing are the two techniques for reaching inside any sequence — a list, a tuple or a string — and pulling out exactly the part you want. Indexing takes one element: Python counts from the front starting at 0, so the first element has index 0, the second has index 1, and so on. Slicing takes a whole portion, using the pattern sequence[start:stop:step], where start is the first index you want, stop is the index you stop before (it is not included), and step is the size of each jump (leave it out and the step is 1).

Then comes the elegant part: negative indices count from the end. −1 means the last element, −2 the second-last, and so on. You never need to know how long a sequence is just to grab its last item. The book's example shows positive and negative indexing and slicing side by side:

# Create a list of fruits
fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
# Indexing
print("First fruit:", fruits[0])    # Positive index → Apple
print("Last fruit:", fruits[-1])    # Negative index → Elderberry
# Slicing with positive indices
print("Fruits from index 1 to 3:", fruits[1:4])    # Banana, Cherry, Date
# Slicing with negative indices
print("Fruits from index -4 to -1:", fruits[-4:-1])  # Banana, Cherry, Date

Notice the last two lines give the same result by two different routes: fruits[1:4] counts from the front, fruits[−4:−1] counts from the back, and both stop before the final element. That symmetry is a good self-check: if the two routes disagree, one of your numbers is wrong.

Class activity — list, tuple and string, all five tasks. The book gives a list [10, 20, 30, 40, 50, 60, 70, 80], a tuple of subjects, and the string "Python Programming". ⚠ One printing slip to correct first: the book's tuple is printed as ("Math" "Science", "English", "History", "Geography") with the comma after "Math" missing — written that way, Python would glue the first two words into one string, "MathScience". The corrected tuple below restores the comma:

numbers = [10, 20, 30, 40, 50, 60, 70, 80]
subjects = ("Math", "Science", "English", "History", "Geography")
text = "Python Programming"
# 1. Third element of each (index 2)
print(numbers[2], subjects[2], text[2])        # 30 English t
# 2. Slice index 2 to 5 from list and tuple
print(numbers[2:5], subjects[2:5])             # [30, 40, 50] ('English', 'History', 'Geography')
# 3. String characters from index 7 to the end
print(text[7:])                                # Programming
# 4. Last two elements with negative indexing
print(numbers[-2:], subjects[-2:])            # [70, 80] ('History', 'Geography')
# 5. Negative slicing: second-last to last character of string
print(text[-2:])                               # ng

Check task 3 by counting the string: P(0) y(1) t(2) h(3) o(4) n(5) space(6) P(7) — so index 7 begins "Programming". And task 5: the string ends …n(…, g), so the last two characters are "ng".

اردو

کسی بھی ترتیب (sequence) — لسٹ، ٹیوپل یا سٹرنگ — کے اندر سے مطلوبہ حصہ نکالنے کے دو طریقے ہیں۔ انڈیکسنگ سے ایک چیز ملتی ہے: گنتی سامنے سے صفر سے شروع ہوتی ہے، پہلی چیز کا انڈیکس 0، دوسری کا 1۔ سلائسنگ سے پورا حصہ ملتا ہے، طریقہ sequence[start:stop:step] ہے: start پہلا مطلوبہ انڈیکس، stop وہ انڈیکس جس سے پہلے رکنا ہے (وہ خود شامل نہیں ہوتا)، step چھلانگ کا سائز ہے۔

خوبصورت حصہ یہ ہے کہ منفی انڈیکس آخر سے گنتے ہیں: −1 آخری چیز، −2 آخری سے دوسری۔ آخری چیز لینے کے لیے لمبائی معلوم ہونا ضروری نہیں۔ مثال: fruits[0] پہلا پھل "Apple"، fruits[−1] آخری "Elderberry"، fruits[1:4] سامنے سے "Banana, Cherry, Date"، اور fruits[−4:−1] پیچھے سے وہی تینوں — دونوں راستے ایک ہی نتیجہ دیں تو سمجھیں عدد درست ہیں۔

کلاس سرگرمی — لسٹ، ٹیوپل اور سٹرنگ: ⚠ کتاب کے ٹیوپل میں "Math" کے بعد کاما چھپنے سے رہ گیا ہے، اس طرح لکھنے سے پائتھون پہلے دو لفظوں کو جوڑ کر "MathScience" بنا دے گا۔ درست ٹیوپل میں کاما بحال کر کے: ہر ایک کا تیسرا رکن 30، English، اور 't' ہے؛ انڈیکس 2 سے 5 تک سلائس [30, 40, 50] اور ('English', 'History', 'Geography') ہے؛ سٹرنگ کے انڈیکس 7 سے آخر تک "Programming" ہے؛ آخری دو رکن [70, 80] اور ('History', 'Geography') ہیں؛ اور سٹرنگ کے آخری دو حروف "ng" ہیں۔

0 / −5Apple1 / −4Banana2 / −3Cherry3 / −2Date4 / −1Elderberryاوپر سے 0, 1, 2… — نیچے سے −1, −2… — دونوں طرف سے وہی چیز ملتی ہے.
Indexing samjho: سامنے سے گنتی 0 سے شروع ہوتی ہے, پیچھے سے −1 سے — آخری چیز کا نام دونوں طرف مختلف ہے, چیز وہی ہے.
2.7 — Modular Programming in Python and the main Function۲.۷ — ماڈیولر پروگرامنگ اور main فنکشن
🏷 Tags: modular programming, modules, main function, __name__, __main__, reuse, calculator module
ENGLISH

Modular programming is the habit of breaking a large program into smaller, manageable, reusable pieces called modules, instead of writing one enormous file where everything is tangled together. The payoff is practical: different parts can be built and tested independently, a piece written for one project can be reused in another, and when something breaks, you know which small piece to look inside. It is the same idea as the packages in section 16, applied to your own code rather than to library code.

Every well-organised Python program also has a clear starting point, and that is the main function. By convention it is a function called main(), placed inside a block that checks whether the script is being run directly or merely imported as a module by someone else:

# main.py
def main():
    print("This is the main function.")
if __name__ == "__main__":
    main()

Here is what happens. Every Python file carries a built-in variable called __name__. When you run the file directly, Python sets __name__ to the special string "__main__", so the check passes and main() runs. But when another file imports this file to borrow its functions, __name__ becomes the file's module name instead, the check fails, and main() politely stays quiet — importing a toolbox should not set off the toolbox's own demo. That distinction is the whole trick, and it is what makes modules safe to share between projects.

Class activity — a calculator module and a main script. The book asks for a module calculator.py with add and subtract functions, and a main.py that imports it, adds 15 and 8, and subtracts 10 from 25 (that is, computes 25 − 10):

# calculator.py
def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
# main.py
import calculator
print(calculator.add(15, 8))       # Output: 23
print(calculator.subtract(25, 10))  # Output: 15

Run main.py and verify both outputs yourself — 15 + 8 = 23 and 25 − 10 = 15 — because the book's own instruction for this activity is to run the script and check that the output is correct, and checking is a habit, not an afterthought.

اردو

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

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

ہر پائتھون فائل میں __name__ نامی بلٹ ان ویری ایبل ہوتا ہے۔ فائل براہ راست چلائیں تو __name__ کی قدر "__main__" ہو جاتی ہے، شرط سچ ہوتی ہے اور main() چلتا ہے۔ لیکن جب کوئی دوسری فائل اسے import کرے تو __name__ فائل کا ماڈیول نام بن جاتا ہے، شرط غلط ہوتی ہے اور main() خاموش رہتا ہے — اوزاروں کا ڈبہ درآمد کرنے سے اس کا اپنا مظاہرہ شروع نہیں ہونا چاہیے۔ یہی فرق ماڈیولز کو منصوبوں میں محفوظ طریقے سے بانٹنے کے قابل بناتا ہے۔

کلاس سرگرمی — کیلکولیٹر ماڈیول: calculator.py میں add اور subtract فنکشن بنائیں، main.py میں اسے import کر کے 15 + 8 = 23 اور 25 − 10 = 15 چھاپیں، اور خود چلا کر دونوں جواب چیک کریں۔

calculator.pyadd() • subtract()main.pyimport calculatorOutput23 aur 15Bara program = chhotay modules + aik main() shuruaat.
Modular samjho: کام چھوٹے modules میں بانٹو, میں.py صرف انہیں جور کر چلائے — خرابی ہو تو صرف ایک module کھولو.
2.8 — Object-Oriented Programming in Python: Classes and Objects۲.۸ — آبجیکٹ اورینٹڈ پروگرامنگ: کلاسز اور آبجیکٹس
🏷 Tags: OOP, class, object, instance, template, __init__, self, method, attributes
ENGLISH

Object-Oriented Programming (OOP) is a way of designing and organising code so that it mirrors the real world: instead of separate piles of data and separate functions, you bundle data and the actions on that data together into objects. A class is the template for creating things, and an object is an actual thing created from that template. The book's toy-car picture explains it better than any definition: to make a toy car you first need a blueprint describing how it should look and work — its colour, its size, its number of wheels, its type of material. That blueprint is not itself a toy car; it is only a plan, and it represents the class. From that one plan you can build many toy cars, each an instance of the class, each following the plan while having its own specific characteristics.

In code, a class is defined with the class keyword, and its special __init__ method runs automatically whenever a new object is created, setting up that object's attributes (its data). A method is simply a function that belongs to a class. The word self is the convention for referring to the particular object inside its own methods — "this car, not cars in general":

# Define a class called ToyCar
class ToyCar:
    # The __init__ method initializes the object with specific attributes
    def __init__(self, color, size, wheels):
        self.color = color   # Color of the toy car
        self.size = size     # Size of the toy car
        self.wheels = wheels  # Number of wheels in the toy car
    # Method to describe the toy car
    def describe(self):
        return f"This toy car is {self.color}, size {self.size}, and has {self.wheels} wheels."
# Create objects of the ToyCar class
car1 = ToyCar("red", "small", 4)
car2 = ToyCar("blue", "large", 6)
# Print descriptions of the toy cars
print(car1.describe())
print(car2.describe())

Follow it through. ToyCar("red", "small", 4) calls __init__ with those three values, which stores them as car1's own colour, size and wheels. car2 gets a completely separate set: blue, large, 6. The outputs are therefore This toy car is red, size small, and has 4 wheels. and This toy car is blue, size large, and has 6 wheels. The class is one blueprint; the two objects are two different cars built from it, each carrying its own data and sharing the same describe method. That — one template, many independent objects — is the whole idea of OOP in one example.

اردو

آبجیکٹ اورینٹڈ پروگرامنگ (OOP) کوڈ کو اس طرح ترتیب دینے کا طریقہ ہے کہ وہ حقیقی دنیا جیسا لگے: ڈیٹا اور اس پر عمل الگ الگ ڈھیروں میں نہیں، بلکہ آبجیکٹس میں ایک ساتھ بندھے ہوتے ہیں۔ کلاس چیزیں بنانے کا سانچہ (template) ہے، اور آبجیکٹ اس سانچے سے بنی اصل چیز ہے۔

کتاب کی کھلونا گاڑی والی مثال اسے بہترین سمجھاتی ہے: کھلونا گاڑی بنانے کے لیے پہلے ایک خاکہ چاہیے جس میں رنگ، سائز، پہیوں کی تعداد اور مواد لکھا ہو۔ وہ خاکہ خود کھلونا گاڑی نہیں، صرف منصوبہ ہے — یہی کلاس ہے۔ اس ایک منصوبے سے کئی گاڑیاں بن سکتی ہیں، ہر ایک کلاس کی انسٹنس ہے، منصوبے پر چلتے ہوئے اپنی اپنی خصوصیات کے ساتھ۔

کوڈ میں کلاس class سے بنتی ہے، اور خاص __init__ میتھڈ ہر نئی آبجیکٹ بنتے وقت خود چل کر اس کی ایٹریبیوٹس (ڈیٹا) طے کرتا ہے۔ میتھڈ کلاس کا اپنا فنکشن ہوتا ہے، اور self کا مطلب ہے "یہی والی آبجیکٹ، عام طور پر سب نہیں"۔ مثال میں car1 سرخ، چھوٹی، 4 پہیوں والی ہے اور car2 نیلی، بڑی، 6 پہیوں والی — ایک سانچہ، دو آزاد گاڑیاں، اور یہی OOP کا پورا خیال ہے۔

Toy car blueprint and toy cars
Class samjho: blueprint ایک ہے (class), اس سے بنی ہر گاڑی الگ ہے (object) — رنگ, size اور پہیے ہر گاڑی کے اپنے.
2.9 — Advanced Python Concepts: Exception Handling and File Handling۲.۹ — اعلیٰ تصورات: غلطیوں سے نمٹنا اور فائل ہینڈلنگ
🏷 Tags: exception handling, try-except, ZeroDivisionError, file handling, open, read, write, append, with statement
ENGLISH

Two skills separate a beginner's program from a robust one: surviving errors gracefully, and remembering data after the program ends. Exception handling manages errors that occur while a program runs, so the program can either carry on or stop politely with a message instead of crashing. File handling reads from and writes to files, which is how data is stored persistently — it is still there tomorrow, when the program's memory is long gone. (Bookkeeping note: the book numbers these subsections 2.9.1.1, then jumps to 2.9.1.4, 2.9.1.5 and 2.9.1.6 — the missing numbers are a printing slip; nothing is missing from the content.)

The tool for handling errors is the try-except block. Code that might fail goes in the try block; if a particular error occurs, Python jumps to the matching except block instead of crashing. The book's example divides 10 by a number the user provides — dangerous, because dividing by zero is an error:

# Input a number from the user
a = int(input("Enter a number: "))
try:
    result = 10 / a  # This line creates an error if the value of 'a' is 0
except ZeroDivisionError:
    print("You can't divide by zero!")

⚠ Scan note: the first line of this example is cut off at the top of the printed page in the scan, so the input line above is reconstructed from the code's own logic (a must come from the user for the division to make sense) and is labelled here as derived, not quoted. With a = 2, result becomes 5.0 and nothing is printed by the except block; with a = 0, Python raises ZeroDivisionError, the except block catches exactly that error, and the screen shows You can't divide by zero! instead of a crash. Catching the specific error name matters: a bare catch-all would also swallow mistakes you actually want to see.

For files, the pattern has three steps: open the file with open(), read or write, then close it to free resources. The with statement does the closing for you automatically, even if an error occurs in between — which is why every example below uses it. To read, open in "r" (read) mode and use read():

# Open and read a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

The with statement guarantees the file is properly closed after its block finishes, so you never have to remember to close it yourself. To write, open in "w" mode — warning: this overwrites anything already in the file — and use write(). To append, open in "a" mode, which adds to the end without touching what is already there:

# Writing to a file
with open("example.txt", "w") as file:
    file.write("As-Salaam-Alaikum, World!\n")
# Appending to a file
with open("example.txt", "a") as file:
    file.write("Appending new line.\n")

After both blocks, example.txt contains two lines: "As-Salaam-Alaikum, World!" followed by "Appending new line." The one-letter mode is the whole difference between keeping old data and destroying it, so read the mode letter twice before you run a write.

اردو

دو مہارتیں ابتدائی پروگرام کو مضبوط پروگرام سے الگ کرتی ہیں: غلطیوں سے نرمی سے نمٹنا، اور پروگرام ختم ہونے کے بعد بھی ڈیٹا یاد رکھنا۔ ایکسپشن ہینڈلنگ چلتے ہوئے پروگرام میں ہونے والی غلطیوں کو سنبھالتی ہے تاکہ پروگرام کریش ہونے کے بجائے جاری رہے یا شائستگی سے رک جائے۔ فائل ہینڈلنگ فائلوں سے پڑھنا اور ان میں لکھنا ہے — اسی طرح ڈیٹا مستقل محفوظ ہوتا ہے، کل بھی موجود رہتا ہے جب پروگرام کی میموری ختم ہو چکی ہوتی ہے۔ (کتاب میں ان ذیلی حصوں کے نمبر 2.9.1.1 کے بعد سیدھے 2.9.1.4، 2.9.1.5، 2.9.1.6 آتے ہیں — درمیانی نمبر چھپائی کی غلطی ہیں، مواد میں کچھ کمی نہیں۔)

غلطی سنبھالنے کا اوزار try-except بلاک ہے: جو کوڈ ناکام ہو سکتا ہے وہ try میں رکھیں، اور اگر مخصوص غلطی ہو تو پائتھون کریش ہونے کے بجائے except بلاک میں چلا جاتا ہے۔ مثال میں 10 کو صارف کے دیے عدد سے تقسیم کیا جاتا ہے — صفر سے تقسیم غلطی ہے۔ ⚠ اسکین میں اس مثال کی پہلی سطر اوپر سے کٹی ہوئی ہے، اس لیے ان پٹ والی سطر یہاں منطق سے دوبارہ بنائی گئی ہے اور اسے اخذ شدہ بتایا جا رہا ہے، نقل نہیں۔ a = 2 ہو تو نتیجہ 5.0 ہے، a = 0 ہو تو ZeroDivisionError پکڑی جاتی ہے اور اسکرین پر "You can't divide by zero!" آتا ہے۔

فائل کے تین قدم ہیں: open() سے کھولیں، پڑھیں یا لکھیں، پھر بند کریں۔ with والا جملہ بند کرنا خود کر دیتا ہے، چاہے درمیان میں غلطی بھی ہو — اسی لیے نیچے کی مثالیں سب with استعمال کرتی ہیں۔ پڑھنے کے لیے "r" موڈ اور read()، لکھنے کے لیے "w" موڈ — خبردار: یہ پرانا مواد مٹا دیتا ہے — اور آخر میں جوڑنے کے لیے "a" موڈ جو پرانا مواد چھوئے بغیر آخر میں لکھتا ہے۔ دونوں بلاکوں کے بعد example.txt میں دو سطریں ہوں گی۔

File open read write close steps
File samjho: کھولو, پڑھو یا لکھو, پھر بند کرو — with یہ بند کرنا خود یاد رکھتا ہے, اور w mode پرانا مٹا دیتا ہے جب کے a mode صرف آخر میں جوڑتا ہے.
2.10 — Testing and Debugging in Python۲.۱۰ — پائتھون میں ٹیسٹنگ اور ڈی بگنگ
🏷 Tags: testing, debugging, unit testing, integration testing, functional testing, regression testing, pdb, error messages
ENGLISH

A program is not finished when it runs once — it is finished when it runs correctly on the inputs it will actually meet. Testing is running your code with various inputs to check that it behaves as expected, with the goal of finding and fixing problems before the code is used in the real world. The book names four types, and each answers a different question. Unit testing tests individual parts — a single function or class — in isolation, and Python's unittest module is commonly used for it. Integration testing checks how different parts work together: a function may be perfect alone and still fail when it meets another part. Functional testing validates that the software behaves as expected from the user's perspective — does the whole thing do what the user asked for? Regression testing makes sure that new changes do not break functionality that already worked — after every fix, re-run the old tests, because fixes have a habit of breaking something else.

Debugging is the other half: the process of finding and fixing errors (bugs) in your code, which means identifying the root cause of a problem and making the necessary changes — not just patching the symptom. The book lists three everyday techniques. Print statements: add temporary prints to check the values of variables at different stages of the code, so you can see where reality first departs from what you expected. Debugging tools: use tools like pdb (Python Debugger) to step through the code line by line, inspect variables, and understand the flow of execution. Error messages: read and interpret the error message itself to locate the source of the problem — Python's messages usually name the file, the line number and the error type, and that trio is often enough to find the bug in seconds. Beginners tend to fear error messages; experienced programmers read them first, because the message is the program telling you exactly where it hurt.

اردو

پروگرام اس وقت مکمل نہیں ہوتا جب وہ ایک بار چل جائے — مکمل تب ہوتا ہے جب وہ ان ان پٹس پر درست چلے جو اسے حقیقت میں ملیں گے۔ ٹیسٹنگ کا مطلب ہے کوڈ کو مختلف ان پٹس کے ساتھ چلا کر جانچنا کہ وہ توقع کے مطابق برتاؤ کرتا ہے یا نہیں، تاکہ مسائل حقیقی استعمال سے پہلے مل کر ٹھیک ہو جائیں۔

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

ڈی بگنگ دوسرا حصہ ہے: کوڈ میں غلطیوں (بگز) کو ڈھونڈنا اور ٹھیک کرنا، یعنی مسئلے کی جڑ پہچان کر ضروری تبدیلی کرنا، صرف ظاہری علامت پر پٹی نہ لگانا۔ تین روزمرہ طریقے: پرنٹ اسٹیٹمنٹس سے مختلف مراحل پر ویری ایبل کی قدریں دیکھیں کہ حقیقت توقع سے کہاں الگ ہوئی؛ ڈی بگنگ ٹولز جیسے pdb سے کوڈ سطر بہ سطر چلائیں اور ویری ایبل دیکھیں؛ اور ایرر میسجز خود پڑھیں — پائتھون کا پیغام عام طور پر فائل، سطر نمبر اور غلطی کی قسم بتاتا ہے، اور یہ تینوں اکثر بگ سیکنڈوں میں ڈھونڈنے کے لیے کافی ہوتے ہیں۔

Test کروmukhtalif inputsBug mila?print / pdb / messageٹھیک کروپھر test کروTest → debug → پھر test: یہی چکر code کو مضبوط بناتا ہے.
Testing samjho: پہلے test سے bug ملتا ہے, پھر debug سے جڑ ملتی ہے, پھر دوبارہ test سے یقین ملتا ہے — ایک دفعہ چلنا کافی نہیں.
📝 Official Exercise Questions — with Answers📝 کتاب کی مشق — جوابات کے ساتھ
KITAB KI EXERCISE

Below are all questions of the Unit 2 exercise from the official book (printed pages 39–40): 9 multiple-choice questions, 8 short questions, and 5 long questions (the book prints the long list as numbers 1–6, but numbers 2 and 3 belong to a single translation question, so they are solved together as one block below). The book has no inquisitive section and no separate review section in this unit, so none is invented here. MCQ keys were cross-checked against the book's Answers page (printed page 141); where that key is wrong, the correction is flagged in the answer itself. Where an answer is derived rather than quoted from a book passage, it says so. Class activities from inside the chapter are already solved in their sections above and are not counted again here.

Multiple Choice Questions

1. An action needed during Python installation to run from the command line easily:

Answer / جواب

Answer: (c) Check "Add Python to PATH" — ticking this box puts Python on the system's command search path, so typing python at a command prompt finds it. Unchecking it (a) does the opposite, and an IDE (b, d) is an editor, not a path setting. PATH میں شامل کرنے سے کمانڈ لائن سے پائتھون آسانی سے چلتا ہے، اس لیے انسٹال کرتے وقت یہ ڈبہ ٹک کرنا ضروری ہے۔

2. A valid variable name in Python is:

Answer / جواب

Answer: (a) variable1 — a name must start with a letter or underscore, and may then contain letters, digits or underscores. (b) starts with a digit, (c) contains a hyphen (which Python reads as minus), and (d) contains a space, so all three are invalid. نام حرف یا انڈر اسکور سے شروع ہو اور بعد میں حرف، ہندسے یا انڈر اسکور آ سکتے ہیں، اس لیے صرف variable1 درست ہے۔

3. Output of the following piece of code is:
age = 25
print("Age : ", age)

Answer / جواب

Answer: (a) Age: 25 — print() displays both arguments: the text "Age : " and the value of age, 25, separated by a space, giving "Age : 25", which option (a) prints as "Age: 25". The other options drop either the label or the value. print دونوں چیزیں دکھاتا ہے: لفظ "Age : " اور age کی قدر 25، اس لیے جواب Age: 25 ہے۔

4. The operator used for exponentiation in Python is:

Answer / جواب

Answer: (b) ** — ** raises to a power (2 ** 3 = 8). (a) * is multiplication, (c) // is floor division, and (d) / is ordinary division. طاقت (power) کے لیے ** استعمال ہوتا ہے، جیسے 2 ** 3 برابر 8 ہے۔

5. A loop used to iterate over a collection such as lists is:

Answer / جواب

Answer: (b) for — a for loop walks through each item of a collection in turn. A while loop (a) repeats while a condition holds rather than over a collection, and Python has no do-while (c) or repeat (d) loop. مجموعے کی ہر چیز پر باری باری چلنے کے لیے for لوپ استعمال ہوتا ہے، پائتھون میں do-while یا repeat لوپ نہیں ہے۔

6. A range() function used to generate a sequence of numbers:

Answer / جواب

Answer: (b) Creates a sequence of numbers — range() produces a sequence of numbers for looping (for example range(5) gives 0, 1, 2, 3, 4). ⚠ Book key warning: the book's Answers page keys this question as (d), but that is wrong — range() does not print anything by itself; printing happens only if you pass its values to print(). Option (a) is also wrong, because a range object is a sequence, not a list. The corrected key is (b), as marked here. range() عددوں کی ترتیب بناتا ہے، خود کچھ نہیں چھاپتا اور یہ لسٹ نہیں ہے، اس لیے درست جواب (b) ہے؛ کتاب کی جوابی کاپی میں (d) لکھا ہے جو غلط ہے۔

7. A keyword used to define a function in Python:

Answer / جواب

Answer: (c) def — functions are defined with def, as in def greet(name):. The words define, function and func are not Python keywords for this purpose. فنکشن بنانے کے لیے def لکھا جاتا ہے، جیسے def greet(name):۔

8. The Output of the following code is:
temperature, humidity, wind_speed = 25, 60, 15
print("Hot and humid" if temperature > 30 and humidity > 50 else "Warm and breezy" if temperature == 25 and wind_speed > 10 else "Cool and dry" if temperature < 20 and humidity < 30 else "Moderate")

Answer / جواب

Answer: (b) Warm — read the chained short-hand expression left to right. First condition: temperature > 30 and humidity > 50 → 25 > 30 is False, so the whole "and" is False and "Hot and humid" is skipped. Second condition: temperature == 25 and wind_speed > 10 → 25 == 25 is True and 15 > 10 is True, so the whole "and" is True and the result is "Warm and breezy". Option (b) prints this as "Warm". The later conditions are never checked, because the first true branch wins. پہلی شرط غلط ہے کیونکہ 25، 30 سے بڑا نہیں، دوسری شرط سچ ہے کیونکہ temperature 25 ہے اور wind_speed 10 سے زیادہ ہے، اس لیے جواب "Warm and breezy" ہے۔

9. The operation used to combine two lists in Python:

Answer / جواب

Answer: (c) + — the + operator concatenates two lists, for example [1, 2] + [3, 4] gives [1, 2, 3, 4]. Python lists have no combine(), concat() or merge() method for this. دو لسٹیں جوڑنے کے لیے + آپریٹر استعمال ہوتا ہے، جیسے [1, 2] + [3, 4] برابر [1, 2, 3, 4] ہے۔

Short Questions

1. Explain the purpose of using comments in Python code.

Comments are lines the interpreter ignores, written for human readers. Their purpose is to explain why code does something — the reasoning, the tricky part, or a warning — so that the code stays understandable weeks later, for yourself and for anyone else who reads it. They do not change what the program does; they change how easily a person can follow it. Single-line comments start with #, and multi-line comments sit between triple quotes '''. کمنٹس وہ سطریں ہیں جنہیں انٹرپریٹر نظر انداز کر دیتا ہے، وہ صرف انسان کے لیے ہوتی ہیں۔ ان کا مقصد یہ بتانا ہے کہ کوڈ ایسا کیوں کرتا ہے، تاکہ بعد میں خود آپ یا کوئی اور اسے آسانی سے سمجھ سکے۔

2. Describe the difference between integer and float data types in Python. Provide an example of each.

An integer (int) stores a whole number with no fractional part, for example age = 17. A float stores a number with a decimal point, for example price = 19.99. The difference shows up in arithmetic: int arithmetic on whole numbers stays whole (7 // 2 = 3), while float arithmetic keeps decimals, and plain division / always produces a float, even for 10 / 2 = 5.0. Choose int for counts and whole quantities, and float for measurements, money and anything that can have a fraction. int مکمل عدد رکھتا ہے جیسے 17، اور float اعشاری عدد رکھتا ہے جیسے 19.99۔ گنتی اور مکمل مقداروں کے لیے int، اور پیمائش یا رقم جیسی چیزوں کے لیے float استعمال کریں۔

3. Define operator precedence and give an example of an expression where operator precedence affects the result.

Operator precedence is the fixed order in which Python evaluates operators in an expression: parentheses first, then exponentiation **, then multiplication, division and modulus, and finally addition and subtraction. It affects the result whenever an expression mixes levels. For example, 3 + 4 * 2 = 11, because multiplication (4 * 2 = 8) happens before addition — but (3 + 4) * 2 = 14, because the parentheses force the addition first. Same numbers, different order, different answer, so brackets are the way to make your intended order unmistakable. آپریٹر پریسیڈنس وہ مقررہ ترتیب ہے جس میں پائتھون آپریٹرز کو چلاتا ہے: پہلے بریکٹ، پھر طاقت، پھر ضرب/تقسیم/موڈولس، آخر میں جمع/تفریق۔ مثال: 3 + 4 * 2 برابر 11 ہے، لیکن (3 + 4) * 2 برابر 14 ہے — بریکٹ نے جواب بدل دیا۔

4. How does the short-hand if-else statement differ from the regular if-else statement?

Both make the same two-way choice, but they differ in shape and in what they are for. A regular if-else is a block: if condition: with an indented block, then else: with its own indented block, and each block can hold many lines. A short-hand if-else squeezes the choice into one expression — value_if_true if condition else value_if_false — and it produces a value that is usually stored or printed, as in m = "It's a hot day" if (temperature > 30) else "It's not a hot day". Use the short-hand for a single simple choice; use the full block whenever either side needs more than one action, because a long one-liner quickly becomes hard to read. دونوں ایک ہی دو طرفہ فیصلہ کرتے ہیں، فرق شکل میں ہے: عام if-else بلاک کی صورت میں ہوتا ہے جس میں ہر طرف کئی سطریں ہو سکتی ہیں، جبکہ مختصر if-else ایک سطر کا ایکسپریشن ہے جو قدر واپس دیتا ہے۔ سادہ فیصلے کے لیے مختصر، لمبے کام کے لیے مکمل بلاک بہتر ہے۔

5. Explain the use of the range() function in a for loop.

range() generates a sequence of numbers that a for loop can walk through, which is exactly what you need when the loop is about counting rather than about items already in a list. range(5) gives 0, 1, 2, 3, 4; range(2, 11, 2) gives 2, 4, 6, 8, 10, stepping by 2; and in general range(start, stop, step) starts at start and stops before stop. So for number in range(3, 31, 3): prints 3, 6, 9, …, 30 — the first ten multiples of 3. Note, as flagged in MCQ 6 above, that range() creates a sequence and prints nothing by itself; it is the print inside the loop that produces output. range() عددوں کی ترتیب بناتا ہے جس پر for لوپ چل سکے، خاص طور پر جب گنتی کرنی ہو نہ کہ لسٹ کی چیزیں دیکھنی ہوں۔ range(2, 11, 2) دیتا ہے 2، 4، 6، 8، 10، اور یاد رکھیں کہ یہ اپنی آخری حد سے پہلے رک جاتا ہے۔

6. Explain how default parameters work in Python functions.

A default parameter is a parameter given a value in the function definition itself, for example def greet(name = "Student"):. When the function is called without an argument for that parameter, Python quietly uses the default — greet() returns "Hello,Student!" (the book's code joins without a space). When the caller does supply an argument, it replaces the default — greet("Umer") returns "Hello, Umer!". Defaults make a function flexible: the common case needs no argument at all, while special cases can still pass their own value. ڈیفالٹ پیرامیٹر وہ قدر ہے جو فنکشن کی تعریف میں ہی لکھ دی جائے، جیسے def greet(name = "Student"):۔ بلانے والا کچھ نہ دے تو یہی قدر استعمال ہوتی ہے، اور اپنی قدر دے تو وہ ڈیفالٹ کی جگہ لے لیتی ہے۔

7. Explain why modular programming is useful in Python.

Modular programming splits a large program into smaller, manageable, reusable pieces called modules, and that division pays off in three ways. First, each piece can be built and tested on its own, so a fault is easier to find. Second, a module written once can be reused in other programs instead of being written again — the calculator module in section 2.7 is an example. Third, a program made of modules is easier to maintain: changing one module does not mean untangling the whole program. The main function then gives the whole assembly one clear starting point. ماڈیولر پروگرامنگ بڑے پروگرام کو چھوٹے، سنبھالنے کے قابل، دوبارہ استعمال ہونے والے حصوں میں توڑ دیتی ہے۔ ہر حصہ الگ آزمایا جا سکتا ہے، ایک بار لکھا حصہ دوسرے پروگرام میں بھی چل سکتا ہے، اور کسی خرابی کو ٹھیک کرنا آسان ہو جاتا ہے۔

8. Explain the difference between a class and an object in Python.

A class is a template or blueprint that describes what things of a kind should have and do — for example, the ToyCar class describes colour, size, wheels and a describe method, but it is not itself a car. An object is an actual thing created from that template, called an instance of the class: car1 = ToyCar("red", "small", 4) is one real toy car, and car2 = ToyCar("blue", "large", 6) is another, each with its own attribute values while sharing the same class. In short: the class is the plan, the object is the product built from the plan, and one class can produce many objects. کلاس سانچہ یا خاکہ ہے جو بتاتا ہے کہ اس قسم کی چیزوں میں کیا ہونا چاہیے، جیسے ToyCar کلاس رنگ، سائز اور پہیے بتاتی ہے مگر خود گاڑی نہیں۔ آبجیکٹ اس سانچے سے بنی اصل چیز ہے، جیسے car1 سرخ چھوٹی گاڑی اور car2 نیلی بڑی گاڑی — ایک سانچہ، کئی آزاد چیزیں۔

Long Questions

L1. Evaluate the following Python expressions. (a) (18 / 3 + 4 ** 2) − (2 * (7 − 3)) / (9 7, 4)   (b) (25 + 3 * 4 ** 2 − 6) / (2 ** 3 + 1) − 7   (c) (12 + 6 * (5 − 2)) ** 2 / ((4 ** 2 − 7) + 10)   (d) 45 / (2 ** 2 + 3 * 4) + 8 * (7 − 3)

(b) Step by step: numerator: 4 ** 2 = 16, so 3 * 16 = 48, and 25 + 48 − 6 = 67. Denominator: 2 ** 3 = 8, so 8 + 1 = 9. Then 67 / 9 = 7.444…, and 7.444… − 7 = 0.444… (exactly 4/9). (c) Step by step: inside: 5 − 2 = 3, 6 * 3 = 18, 12 + 18 = 30, and 30 ** 2 = 900. Denominator: 4 ** 2 = 16, 16 − 7 = 9, 9 + 10 = 19. So 900 / 19 = 47.368…. (d) Step by step: denominator: 2 ** 2 = 4, 3 * 4 = 12, 4 + 12 = 16, so 45 / 16 = 2.8125. Then 8 * (7 − 3) = 8 * 4 = 32. Total: 2.8125 + 32 = 34.8125. (a) ⚠ Cannot be evaluated as printed: the denominator in the book is garbled — it reads "(9 7, 4)", which is not valid Python and cannot be read reliably even at high resolution, so no definitive answer is invented here. The readable part evaluates as follows: 18 / 3 = 6, 4 ** 2 = 16, so the first bracket is 22; and 2 * (7 − 3) = 8. If the denominator were meant to be 9, the result would be 22 − 8/9 = 21.111… — but that reading is only a guess, clearly labelled as such, and the question as printed should be treated as misprinted. (b) کا جواب 4/9 یعنی تقریباً 0.444 ہے، (c) کا جواب 900/19 یعنی تقریباً 47.37 ہے، (d) کا جواب 34.8125 ہے۔ حصہ (a) جیسا چھپا ہے اسے حل نہیں کیا جا سکتا کیونکہ اس کا مخرج (denominator) چھپائی میں بگڑا ہوا ہے، اس لیے اس کا کوئی حتمی جواب نہیں بنایا گیا۔

L2. Translate the following mathematical expressions to Python syntax. (Book numbers this as questions 2 and 3; it is one translation question, so it is solved here as a single block.) (a) 5 × (3 + 2²) over (6 − 2 × 3)   (b) 7 + 2²

(a) Translation: 5 * (3 + 2 ** 2) / (6 − 2 * 3). ⚠ Flawed as an evaluation: the denominator is 6 − 2 * 3 = 6 − 6 = 0, so running this expression in Python raises ZeroDivisionError — it has no numerical value. The translation itself is correct, but the expression as set cannot be evaluated; the numerator alone is 5 * (3 + 4) = 35. (b) Translation and value: 7 + 2 ** 2. The power comes first (2 ** 2 = 4), then 7 + 4 = 11. (a) کا پائتھون ترجمہ 5 * (3 + 2 ** 2) / (6 − 2 * 3) ہے، لیکن اس کا مخرج صفر بنتا ہے (6 − 6 = 0) اس لیے اسے چلانے پر ZeroDivisionError آئے گی اور اس کی کوئی عددی قدر نہیں۔ (b) کا ترجمہ 7 + 2 ** 2 ہے اور جواب 11 ہے۔

L3. Explain the concept of variables in Python.

A variable is a named storage container in the computer's memory that holds a value which can be retrieved and changed while a program runs. You create one by assignment — name = value — for example age = 17 stores 17 under the name age, and a later line age = 18 replaces it, so a later print shows 18. The name must start with a letter or underscore, may then contain letters, digits or underscores, is case-sensitive (age and Age are different variables), and cannot be one of Python's reserved keywords such as for, while or if. Variables also carry a data type that says what kind of value they hold: int for whole numbers (age = 17), float for decimals (price = 19.99), str for text (name = "Ali"), and bool for True or False (is_student = True). Good names are meaningful and lowercase with underscores, like student_name, so that a reader can guess what the container holds. Without variables, a program could only work with fixed numbers written into the code; with them, the same code can handle any input the user gives. ویری ایبل کمپیوٹر کی میموری میں نام والا ڈبہ ہے جس میں قدر رکھی جاتی ہے اور پروگرام چلتے ہوئے اسے بدلا جا سکتا ہے۔ اسے assignment سے بناتے ہیں، جیسے age = 17، اور بعد میں age = 18 لکھنے سے وہی ڈبہ نئی قدر دکھانے لگتا ہے۔ نام حرف یا انڈر اسکور سے شروع ہو، کیس سینسٹیو ہو، اور مخصوص الفاظ نہ ہو۔ قدر کی قسم بھی ہوتی ہے: int مکمل عدد، float اعشاری، str لفظ، اور bool صرف True یا False۔

L4. Write a Python program that takes a number as input and checks whether it is positive, negative, or zero using an if-elif-else statement.

The program reads a whole number with int(input(…)), then walks the if-elif-else ladder: above zero is positive, below zero is negative, and anything left over — only zero — falls into the else. Try it with 5 (Positive number), −3 (Negative number) and 0 (Zero):
number = int(input("Enter a number: "))
if number > 0:
    print("Positive number")
elif number < 0:
    print("Negative number")
else:
    print("Zero")

Why the ladder works: only the first true branch runs, so a positive number never reaches the elif, a negative number skips the if and stops at the elif, and zero fails both checks and is caught by the else. The int() conversion matters here too — without it, input would give a string and the comparisons with 0 would fail. پروگرام پہلے int(input(...)) سے مکمل عدد لیتا ہے، پھر if-elif-else سیڑھی چلاتا ہے: صفر سے بڑا ہو تو Positive، صفر سے چھوٹا ہو تو Negative، ورنہ else سے Zero۔ 5 ڈالیں تو Positive، −3 ڈالیں تو Negative، اور 0 ڈالیں تو Zero آئے گا۔ int() اس لیے ضروری ہے کہ بغیر اس کے ان پٹ لفظ ہوتا اور صفر سے موازنہ نہ ہو پاتا۔

L5. Write a Python program using a while loop that prints all the odd numbers between 1 and 100. Also, count and print the total number of odd numbers.

Start a counter at 1 and an odd counter at 0. While the counter is at most 100, test it with % 2: a remainder of 1 means odd, so print it and add 1 to the odd counter; then always move the counter on by 1, or the loop would never end. After the loop, print the total:
number = 1
odd_count = 0
while number <= 100:
    if number % 2 == 1:
        print(number)
        odd_count += 1
    number += 1
print("Total odd numbers:", odd_count)

The printed odds are 1, 3, 5, …, 99, and the final line is Total odd numbers: 50 — exactly half of the numbers from 1 to 100 are odd, which is a good check that the count is right. کاؤنٹر 1 سے شروع کریں اور طاق عددوں کا کاؤنٹر صفر سے۔ جب تک کاؤنٹر 100 یا اس سے کم ہو، % 2 سے جانچیں: باقی 1 ہو تو عدد طاق ہے، اسے چھاپیں اور طاق کاؤنٹر میں ایک بڑھائیں، پھر کاؤنٹر میں ایک بڑھائیں ورنہ لوپ کبھی ختم نہ ہوگا۔ آخر میں جواب آئے گا: Total odd numbers: 50، کیونکہ 1 سے 100 میں طاق عدد پچاس ہیں۔

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

This chapter takes you from "what is a program?" to writing programs that decide, repeat, organise and survive errors. It starts with Python itself and a working setup (IDE, PATH), then the first program and comments, then the heart of everyday coding: variables, naming rules, data types, input and output, and converting text input into real numbers. From there it builds the toolkit in order — arithmetic, comparison, assignment, logical operators, expressions and precedence — before teaching the two great control ideas, decision making (if, if-else, short-hand if-else, if-elif-else) and looping (while, for, range). Then it steps up a level: functions with parameters, return values and defaults; libraries, modules and packages; the built-in containers lists and tuples; indexing and slicing from both ends; modular programming with a main function; classes and objects; exception handling and file handling; and finally testing and debugging.

Topics covered: Introduction & setup • Syntax & comments • Variables & data types • Input/output & conversions • Arithmetic operators • Comparison operators • Assignment operators • Logical operators & expressions • Precedence & BMI • if statement • if-else & short-hand • if-elif-else • while loop • for loop & range • Functions • Libraries & packages • Lists • Tuples • Indexing & slicing • Modular programming • Classes & objects • Exceptions & files • Testing & debugging • Official exercise

Revision guidance: three things carry the most marks. First, the operators and their order — precedence questions and the long-expression evaluations reward anyone who works step by step on paper. Second, the control structures: be able to trace an if-elif-else ladder and a while loop by hand, watching the variable change each round. Third, the short programs: even/odd, positive/negative/zero, odds from 1 to 100, and a function with a return value. Type every program in this chapter and run it — reading code is not the same skill as writing it, and the exam tests the second one. And keep the flagged book warnings in mind (MCQ 6's key, the BMI square, the assignment trace, the garbled long question): in an exam, trust the language's rules over a misprinted line.

اردو

یہ باب آپ کو "پروگرام کیا ہے؟" سے لے کر ایسے پروگرام لکھنے تک لے جاتا ہے جو فیصلہ کریں، دہرائیں، منظم ہوں اور غلطیوں سے بچیں۔ شروع میں پائتھون اور اس کا سیٹ اپ (IDE، PATH)، پھر پہلا پروگرام اور کمنٹس، پھر روزمرہ کوڈنگ کی بنیاد: ویری ایبلز، ناموں کے اصول، ڈیٹا کی اقسام، ان پٹ/آؤٹ پٹ، اور لفظی ان پٹ کو اصلی عدد میں بدلنا۔ پھر اوزار ترتیب سے آتے ہیں — حسابی، موازنہ، اسائنمنٹ، منطقی آپریٹرز، ایکسپریشنز اور ترجیح — پھر دو بڑے کنٹرول خیالات: فیصلہ سازی (if، if-else، مختصر if-else، if-elif-else) اور لوپنگ (while، for، range)۔ پھر اگلا درجہ: فنکشنز، لائبریریاں اور پیکجز، لسٹس اور ٹیوپلز، انڈیکسنگ اور سلائسنگ، ماڈیولر پروگرامنگ، کلاسز اور آبجیکٹس، غلطیوں سے نمٹنا اور فائل ہینڈلنگ، اور آخر میں ٹیسٹنگ اور ڈی بگنگ۔

دہرائی کی رہنمائی: تین چیزیں سب سے زیادہ نمبر دلاتی ہیں: آپریٹرز اور ان کی ترتیب (لمبے ایکسپریشن کاغذ پر مرحلہ وار حل کریں)، کنٹرول اسٹرکچرز (if-elif-else سیڑھی اور while لوپ کو ہاتھ سے ٹریس کریں، ہر دور میں ویری ایبل کی تبدیلی دیکھیں)، اور چھوٹے پروگرام (جفت/طاق، مثبت/منفی/صفر، 1 سے 100 تک طاق عدد، اور return والا فنکشن)۔ اس باب کا ہر پروگرام خود ٹائپ کر کے چلائیں — کوڈ پڑھنا اور کوڈ لکھنا دو الگ مہارتیں ہیں، اور امتحان دوسری کو جانچتا ہے۔ اور کتاب کی نشاندہی شدہ تنبیہات (MCQ 6 کی کلید، BMI کا مربع، اسائنمنٹ کا حساب، بگڑا ہوا طویل سوال) ذہن میں رکھیں: امتحان میں غلط چھپی سطر کے بجائے زبان کے اصولوں پر بھروسہ کریں۔

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

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

PunjabTest.com — Tests →

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

← Chapter 1FSc Part 1: Computer Science — all chaptersChapter 3 →