A name must start with a letter or underscore and may contain only letters, digits and underscores. 1variable starts with a digit, variable-name has a hyphen and variable name has a space.
Ex 2 · QMCQ 3MCQ1 mark
Output of the following piece of code is:
```
age = 25
print(" Age : ", age)
```
Functions are defined with def, e.g. def greet(name):
Ex 2 · QMCQ 8MCQ1 mark
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:Comments are notes in the code that Python does not execute. They explain what the code does, make it easier to read and maintain, and can temporarily disable lines.
Solution
**Comments** are lines ignored by the Python interpreter.
- Single-line comment: starts with #.
- Multi-line comment: text between triple quotes.
**Purpose:**
1. Explain the logic so that others (and you, later) understand the code.
2. Make maintenance and debugging easier.
3. Temporarily switch off a line of code while testing.
```
# calculate the area of a circle
area = 3.14 * r * r
```
Ex 2 · QShort 2Short2 marks
Describe the difference between integer and float data types in Python. Provide an example of each.
Answer:int stores whole numbers without a decimal point (age = 17); float stores numbers with a decimal point (price = 19.99).
Solution
- **Integer (int):** whole numbers, positive or negative, no decimal part. Example: age = 17, marks = -5.
- **Float (float):** real numbers with a decimal point (fractional part). Example: price = 19.99, height = 1.75.
Dividing with / always gives a float: 10 / 2 = 5.0. Convert input with int(input()) or float(input()).
Ex 2 · QShort 3Short2 marks
Define operator precedence and give an example of an expression where operator precedence affects the result.
Answer:Operator precedence is the order in which Python performs operations in an expression: `( )`, then `**`, then `* / // %`, then `+ -`. Example: `2 + 3 * 4` = 14, but `(2 + 3) * 4` = 20.
Solution
**Operator precedence** decides which operation is done first when an expression has several operators.
Order: parentheses `( )` → `**` → `*, /, //, %` → `+, -`.
**Example:**
```
print(2 + 3 * 4) # 14 (multiplication first)
print((2 + 3) * 4) # 20 (parentheses first)
```
Without knowing precedence one might expect 20 for the first line, but Python gives 14.
Ex 2 · QShort 4Short2 marks
How does the short-hand if-else statement differ from the regular if-else statement?
Answer:The short-hand if-else (conditional expression) is written on one line and gives a value: x if condition else y. The regular if-else uses separate indented blocks and can contain many statements.
Solution
**Regular if-else:** several lines, indented blocks, each block may hold many statements.
```
if n % 2 == 0:
print("Even")
else:
print("Odd")
```
**Short-hand if-else:** one line; it is an expression that produces a value – good for simple choices.
```
print("Even" if n % 2 == 0 else "Odd")
```
So the short-hand form is shorter but only suitable for a single simple choice.
Ex 2 · QShort 5Short2 marks
Explain the use of the range() function in a for loop.
Answer:range(start, stop, step) produces a sequence of numbers that the for loop goes through, so the loop runs a fixed number of times; stop is not included.
Solution
range() generates the numbers the loop variable takes:
- range(5) → 0, 1, 2, 3, 4
- range(1, 6) → 1, 2, 3, 4, 5
- range(2, 11, 2) → 2, 4, 6, 8, 10
```
for i in range(1, 11):
print(3 * i) # first 10 multiples of 3
```
The stop value is never included; step is optional (default 1).
Ex 2 · QShort 6Short2 marks
Explain how default parameters work in Python functions.
Answer:A default parameter has a value given in the function definition; if the caller does not pass that argument, the default value is used, otherwise the passed value replaces it.
Solution
```
def greet(name="Student"):
return "Hello " + name + "!"
print(greet()) # Hello Student!
print(greet("Umer")) # Hello Umer!
```
In the first call no argument is given, so name takes the default "Student". In the second call "Umer" overrides it. Default parameters must come after the parameters that have no default.
Ex 2 · QShort 7Short2 marks
Explain why modular programming is useful in Python.
Answer:It divides a big program into small, reusable modules, so code is easier to understand, test, maintain and reuse, and different people can work on different modules at the same time.
Solution
**Modular programming** splits a program into separate modules (files of related functions).
**Benefits:**
1. **Manageable** – each module is small and handles one part of the problem.
2. **Reusable** – a module (e.g. calculator.py) can be imported into many programs.
3. **Teamwork** – developers work on different modules independently.
4. **Easy testing and maintenance** – a bug is found and fixed in one module without touching the rest.
Example: main.py imports calculator.py and calls calculator.add(15, 8).
Ex 2 · QShort 8Short2 marks
Explain the difference between a class and an object in Python.
Answer:A class is a template/blueprint that defines attributes and methods; an object is an actual instance created from a class with its own attribute values.
Solution
- **Class:** a blueprint or plan – it describes what data (attributes) and actions (methods) its objects will have. It is not a real thing itself.
- **Object:** a real instance made from the class, with its own values.
```
class ToyCar:
def __init__(self, color):
self.color = color
car1 = ToyCar("red") # object 1
car2 = ToyCar("blue") # object 2
```
ToyCar is the class; car1 and car2 are two objects of it, each with its own color.
Translate the following mathematical expressions to Python syntax.
(a) 5 × (3 + 2²) ÷ (6 − 2 × 3) (written in the book as a fraction: 5 × (3 + 2²) over 6 − 2 × 3)
(b) 7 + 2²
× becomes `*`, a power becomes `**`, a fraction bar becomes / with brackets round the top and the bottom.
**(a)**
```
5 * (3 + 2 ** 2) / (6 - 2 * 3)
```
Note: the bottom `6 - 2 * 3` = 0, so running it gives **ZeroDivisionError: division by zero** (the top is 5 * 7 = 35). It can be guarded with try / except ZeroDivisionError.
**(b)**
```
7 + 2 ** 2
```
Value: `2 ** 2` = 4, 7 + 4 = **11**.
Answer:A variable is a named storage location in memory that holds a value which can change during the program. It is created by assignment (age = 17), its type is decided by the value (int, float, str, bool), and its name must follow Python's naming rules.
Solution
**Variable:** a storage container in the computer's memory with a name; it allows storing, retrieving and changing data. The value can change while the program runs.
```
age = 71
print("Ahmad lived for", age, "years")
age = 60 # same variable, new value
print("Iqbal lived for", age, "years")
```
**Creating variables:** Python needs no declaration – a variable is created when a value is assigned with =. Its type comes from the value (dynamic typing):
- int: age = 17 - float: price = 19.99 - str: name = "Ali" - bool: is_student = True
**Naming rules:**
1. Start with a letter or underscore.
2. Then only letters, digits and underscores.
3. Case-sensitive (age ≠ Age).
4. Keywords (if, for, while ...) are not allowed.
**Good practice:** meaningful lowercase names with underscores, e.g. student_name instead of a.
**Input into variables:** name = input("Enter name: "), marks = int(input("Enter marks: ")).
Ex 2 · QLong 5LongProgram5 marks
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.
Answer:Read the number with float(input()), then if n > 0 print Positive, elif n < 0 print Negative, else print Zero.
Solution
```
# Check whether a number is positive, negative or zero
num = float(input("Enter a number: "))
if num > 0:
print(num, "is a positive number")
elif num < 0:
print(num, "is a negative number")
else:
print("The number is zero")
```
**Sample runs:**
- Enter a number: 7 → 7.0 is a positive number
- Enter a number: -3.5 → -3.5 is a negative number
- Enter a number: 0 → The number is zero
**Explanation:** the if condition is checked first; if it is False, elif is checked; if both are False, the else block runs. float() is used so decimals are also accepted.
Ex 2 · QLong 6LongProgram5 marks
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.
Answer:Start with num = 1 and count = 0; while num <= 100: if num % 2 != 0 print it and add 1 to count; num += 1. Finally print count → 50 odd numbers.
Solution
```
# Print odd numbers from 1 to 100 and count them
num = 1
count = 0
while num <= 100:
if num % 2 != 0: # odd number
print(num, end=" ")
count += 1
num += 1
print()
print("Total odd numbers:", count)
```
**Output:**
1 3 5 7 ... 97 99
Total odd numbers: **50**
**Explanation:** the loop runs while num is not more than 100. num % 2 != 0 is True for odd numbers, which are printed and counted. num += 1 moves to the next number so the loop ends. (A shorter version adds 2 each time starting from 1.)