Unit 1 subjective questions Python basics
ECAP776 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define Python and explain its major features and applications.
Model answer
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum. It emphasizes readability and developer productivity.
Major features:
- Simple syntax: Programs are concise and easy to understand.
- Interpreted: Statements are executed by an interpreter without a separate compilation step.
- Dynamically typed: Variable types are determined at runtime.
- Object-oriented: Python supports classes, objects, inheritance, and polymorphism.
- Portable: The same program can run on multiple operating systems with few or no changes.
- Open source: Python is freely available and supported by a large community.
- Extensive libraries: Its standard library and third-party ecosystem provide modules for many tasks.
Applications:
- Web development
- Data analysis and visualization
- Artificial intelligence and machine learning
- Scientific computing
- Automation and scripting
- Desktop application development
- Software testing
-
Question 2 of 20
Explain how a Python program is executed. Distinguish between interactive mode and script mode.
Model answer
Python generally performs the following steps when executing a program:
- The interpreter reads and checks the source code.
- It converts the source code into an intermediate form called bytecode.
- The Python Virtual Machine (PVM) executes the bytecode.
- Errors encountered during translation or execution are reported to the programmer.
Interactive mode:
- Commands are entered directly at the Python prompt.
- Each command is executed immediately.
- It is useful for experimentation and testing short statements.
- Commands are not automatically saved as a reusable program.
Script mode:
- Statements are saved in a file, commonly with the
.pyextension. - The entire file is executed by the Python interpreter.
- It is suitable for larger and reusable programs.
- The source code can be edited, shared, tested, and maintained.
Thus, interactive mode is convenient for quick exploration, whereas script mode is preferred for application development.
-
Question 3 of 20
What are identifiers, keywords, variables, and literals in Python? State the rules for naming identifiers.
Model answer
- An identifier is a name used to identify a variable, function, class, module, or another program element.
- A keyword is a reserved word with a predefined meaning, such as
if,else,for,def, andreturn. It cannot be used as an identifier. - A variable is a name bound to an object or value. For example,
age = 20bindsageto the integer20. - A literal is a fixed value written directly in source code, such as
10,3.5,"Python", orTrue.
Rules for identifiers:
- An identifier may contain letters, digits, and underscores.
- It must begin with a letter or underscore, not a digit.
- It cannot be a Python keyword.
- It cannot contain spaces or symbols such as
@,%, and-. - Identifiers are case-sensitive;
totalandTotalare different. - Meaningful names following the
snake_caseconvention are recommended.
Examples of valid identifiers include
student_name,_count, andvalue2. Examples of invalid identifiers include2value,student-name, andfor. -
Question 4 of 20
Describe Python's basic built-in data types with suitable examples.
Model answer
Python provides several built-in data types:
- Integer (
int): Represents whole numbers, such as25,0, and-12. - Floating-point (
float): Represents decimal or exponential values, such as3.14and2.5e3. - Complex (
complex): Represents numbers with real and imaginary parts, such as2 + 3j. - Boolean (
bool): RepresentsTrueorFalse. - String (
str): Represents text, such as"Python". - List (
list): An ordered, mutable collection, such as[10, 20, 30]. - Tuple (
tuple): An ordered, immutable collection, such as(10, 20, 30). - Range (
range): Represents an arithmetic sequence, such asrange(1, 6). - Set (
set): An unordered collection of unique elements, such as{1, 2, 3}. - Dictionary (
dict): Stores key-value pairs, such as{"name": "Asha", "age": 20}. - None type (
NoneType): Represents the absence of a value throughNone.
The type of an object can be inspected using
type(value). - Integer (
-
Question 5 of 20
Distinguish between mutable and immutable data types in Python. Explain the distinction using examples.
Model answer
A mutable object can be changed after it is created, whereas an immutable object cannot be changed after creation.
Mutable types:
- Include lists, dictionaries, and sets.
- Their contents can be added, removed, or replaced without creating a different container.
- Example: after
values = [1, 2, 3], the statementvalues[0] = 10changes the list to[10, 2, 3].
Immutable types:
- Include integers, floating-point numbers, booleans, strings, and tuples.
- An apparent modification creates and binds a new object instead of changing the existing object.
- Example: if
text = "cat", the expressiontext + "s"produces a new string. Individual characters cannot be assigned usingtext[0] = "b".
Importance of the distinction:
- Mutable objects can be modified through any reference pointing to them.
- Immutable objects are safer when fixed values are required.
- Only suitable hashable objects, commonly immutable values, may be used as dictionary keys or set elements.
-
-
Question 6 of 20
Explain implicit and explicit type conversion in Python. Illustrate both with examples and mention possible conversion errors.
Model answer
Implicit conversion is performed automatically by Python when compatible data types are used together. It generally converts a narrower numeric type to a broader one to preserve information.
Example:
- If
a = 5andb = 2.5, thena + bproduces7.5. - Python converts the integer
5to the floating-point value5.0during the operation.
Explicit conversion, also called type casting, is requested by the programmer using conversion functions:
int("25")gives25.float(4)gives4.0.str(100)gives"100".list((1, 2))gives[1, 2].
Important considerations:
int(3.9)gives3; it truncates the fractional part rather than rounding.int("12.5")raisesValueErrorbecause the string is not a valid integer literal.int("abc")also raisesValueError.- Some unrelated types cannot be converted and may cause
TypeError.
Explicit conversion should therefore be performed only after validating the input.
- If
-
Question 7 of 20
Classify and explain the operators available in Python with suitable examples.
Model answer
Python operators can be classified as follows:
- Arithmetic operators:
+,-,*,/,//,%, and**. For example,7 // 2is3,7 % 2is1, and2 ** 3is8. - Comparison operators:
==,!=,<,>,<=, and>=. They produce Boolean results; for example,5 > 2isTrue. - Assignment operators:
=,+=,-=,*=,/=, and others. For example,x += 2is equivalent tox = x + 2. - Logical operators:
and,or, andnot. For example,True and FalsegivesFalse. - Bitwise operators:
&,|,^,~,<<, and>>. They operate on integer bits. - Membership operators:
inandnot in. For example,"a" in "cat"givesTrue. - Identity operators:
isandis not. They test whether operands refer to the same object.
The correct operator depends on whether a program needs arithmetic, comparison, logical combination, bit manipulation, membership testing, or object identity testing.
- Arithmetic operators:
-
Question 8 of 20
Explain operator precedence and associativity in Python. Evaluate the expression
2 + 3 * 4 ** 2 // 8 - 1step by step.Model answer
Operator precedence determines which operation is performed first. Associativity determines the evaluation direction when operators have the same precedence.
A simplified high-to-low precedence order is:
- Parentheses
- Exponentiation
- Unary operators
- Multiplication, division, floor division, and remainder
- Addition and subtraction
- Comparisons
- Logical
not,and, andor
Most binary operators are left-associative, but exponentiation is right-associative. Parentheses can be used to make the intended order explicit.
For
2 + 3 * 4 ** 2 // 8 - 1:- Exponentiation:
4 ** 2 = 16 - Multiplication:
3 * 16 = 48 - Floor division:
48 // 8 = 6 - Addition and subtraction proceed from left to right:
2 + 6 - 1 = 7
Therefore, the final value is
7. -
Question 9 of 20
Compare the
/,//,%, and**operators in Python. Explain how floor division and remainder are related.Model answer
/performs true division and normally returns a floating-point value. For example,7 / 2gives3.5.//performs floor division. It returns the greatest integer less than or equal to the exact quotient. Thus,7 // 2gives3, while-7 // 2gives-4.%produces the remainder associated with floor division. For example,7 % 2gives1, while-7 % 2gives1.**performs exponentiation. For example,2 ** 5gives32.
For a nonzero divisor , floor division and remainder satisfy:
For and :
- Therefore, .
The remainder has the same sign as the divisor in Python, unless it is zero.
-
Question 10 of 20
Differentiate between equality, identity, and membership operations in Python.
Model answer
Equality:
- The operators
==and!=compare the values of two objects. - For example,
[1, 2] == [1, 2]is normallyTruebecause the lists contain equal values.
Identity:
- The operators
isandis notcheck whether two references point to the exact same object. - If
a = [1, 2]andb = [1, 2], thena == bisTrue, buta is bisFalsebecause two separate lists were created. - If
c = a, thenc is aisTrue. isshould commonly be used for singleton comparisons such asvalue is None.
Membership:
- The operators
inandnot incheck whether an item occurs in a collection. 2 in [1, 2, 3]isTrue.- In a dictionary, membership checks keys by default. Thus,
"name" in {"name": "Asha"}isTrue.
Equality compares content, identity compares object references, and membership tests containment.
- The operators
-
Question 11 of 20
Explain simple
if,if-else, andif-elif-elsestatements in Python. Why is indentation significant?Model answer
Conditional statements select statements for execution according to Boolean conditions.
- A simple
ifstatement executes its block only when its condition is true. - An
if-elsestatement selects between two alternatives. - An
if-elif-elsestatement evaluates multiple conditions in order. The first true branch is executed; if no condition is true, theelseblock is executed.
Example:
score = 72 if score >= 75: grade = "Distinction" elif score >= 50: grade = "Pass" else: grade = "Fail"Here,
gradebecomes"Pass".Significance of indentation:
- Python uses indentation to define a block of statements.
- Statements at the same indentation level belong to the same block.
- Inconsistent indentation can raise
IndentationErroror alter program logic. - Four spaces per indentation level is the standard convention.
Conditions may use comparisons, logical operators, or any expression whose truth value can be evaluated.
- A simple
-
Question 12 of 20
Describe nested conditional statements and logical operators. Write the logic for determining whether a given year is a leap year.
Model answer
A nested conditional is an
ifstatement placed inside another conditional block. It is useful when a second decision depends on the result of a first decision. Logical operators can often express the same rules more concisely:andis true when both operands are true.oris true when at least one operand is true.notreverses a truth value.
A year is a leap year when it is divisible by
400, or when it is divisible by4but not by100. The condition is:if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): print("Leap year") else: print("Not a leap year")The same rule can be implemented using nested conditions, but the combined logical expression directly represents the mathematical rule. Parentheses improve readability and make the grouping explicit.
-
Question 13 of 20
Explain the
whileloop in Python. Write and trace a program that calculates the sum of the first natural numbers.Model answer
A
whileloop repeatedly executes a block as long as its condition remains true. It is appropriate when the number of iterations is not known in advance.Program:
n = int(input("Enter n: ")) i = 1 total = 0 while i <= n: total += i i += 1 print(total)For , the trace is:
- Initially,
i = 1andtotal = 0. - Iteration 1:
total = 1,i = 2. - Iteration 2:
total = 3,i = 3. - Iteration 3:
total = 6,i = 4. - Iteration 4:
total = 10,i = 5. - The condition
i <= 4becomes false, so the loop stops.
The result also agrees with:
For , . The update
i += 1is essential; omitting it would create an infinite loop. - Initially,
-
Question 14 of 20
Explain the
forloop and therange()function. Compareforandwhileloops with examples of suitable use cases.Model answer
A
forloop iterates over the elements of an iterable such as a string, list, tuple, dictionary, or range.The function
range(start, stop, step)generates an arithmetic sequence:startis included and defaults to0.stopis excluded.stepdefaults to1and cannot be zero.
For example,
range(2, 10, 2)produces2, 4, 6, 8during iteration.for value in range(2, 10, 2): print(value)Comparison:
- A
forloop is preferred when iterating through a collection or when the number of repetitions is known. - A
whileloop is preferred when repetition depends on a condition and the number of iterations is uncertain. - A
forloop automatically obtains successive elements. - A
whileloop normally requires explicit initialization and updating of a control variable.
For example, processing every name in a list suits a
forloop, while repeatedly requesting input until the user enters"quit"suits awhileloop. -
Question 15 of 20
Describe the purpose of
break,continue, andpassin Python. How does the optionalelseclause of a loop behave?Model answer
break: Immediately terminates the nearest enclosing loop. Execution resumes after the loop.continue: Skips the rest of the current iteration and starts the next iteration.pass: Performs no action. It is a syntactic placeholder used where a statement is required.
Example:
for number in range(1, 6): if number == 2: continue if number == 5: break print(number)This prints
1,3, and4. The value2is skipped, and the loop ends when the value becomes5.A loop's optional
elseclause executes when the loop ends normally, including when aforloop exhausts its iterable or awhilecondition becomes false. It does not execute if the loop is terminated bybreak. This behavior is useful in searches: theelseblock can report that no matching item was found. -
Question 16 of 20
What is a function in Python? Explain function definition, function call, parameters, arguments, and return values.
Model answer
A function is a named, reusable block of code designed to perform a specific task. Functions improve modularity, readability, testing, and code reuse.
A function is defined with the
defkeyword:def area_rectangle(length, width): area = length * width return area result = area_rectangle(5, 3)Terminology:
area_rectangleis the function name.lengthandwidthare parameters, which are names in the function definition.5and3are arguments, which are actual values supplied during the call.area_rectangle(5, 3)is the function call.return areasends the computed result back to the caller.
A function without an explicit
returnstatement returnsNone. Areturnstatement also ends that invocation immediately. A function may return multiple comma-separated values; Python packages them into a tuple. -
Question 17 of 20
Compare positional, keyword, default, and variable-length arguments in Python functions.
Model answer
Positional arguments:
- Values are matched to parameters according to their order.
- Example:
power(2, 3)assigns2to the first parameter and3to the second.
Keyword arguments:
- Values are associated with parameters by name.
- Example:
power(exponent=3, base=2)improves clarity and allows rearrangement of keyword arguments.
Default arguments:
- A parameter receives a predefined value when the caller omits it.
- In
def greet(name, message="Hello"), callinggreet("Mira")uses"Hello". - Parameters with defaults generally follow parameters without defaults.
Variable-length arguments:
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.
Example:
def report(title, *scores, **details): return title, scores, detailsCalling
report("Test", 80, 90, subject="Python")produces a title, the tuple(80, 90), and the dictionary{"subject": "Python"}.These argument forms allow functions to balance strict interfaces with flexibility.
-
Question 18 of 20
Explain local, global, and nonlocal scope in Python using the LEGB name-resolution rule.
Model answer
Python resolves names using the LEGB rule:
- Local: Names defined inside the current function.
- Enclosing: Names in enclosing functions when functions are nested.
- Global: Names defined at module level.
- Built-in: Predefined names such as
lenandprint.
A local variable normally exists only during a function call and does not directly change a global variable with the same name. The
globalstatement allows a function to rebind a module-level name.The
nonlocalstatement is used in a nested function to rebind a name in the nearest enclosing function scope:def outer(): count = 0 def inner(): nonlocal count count += 1 inner() return countHere,
inner()modifies thecountbelonging toouter(), soouter()returns1.Excessive use of global state can make programs difficult to test and maintain. Passing values as arguments and returning results is generally clearer.
-
Question 19 of 20
Define recursion. Explain how a recursive factorial function works, including its base case and recursive case.
Model answer
Recursion is a technique in which a function calls itself to solve a smaller instance of the same problem. Every correct recursive solution needs:
- A base case that stops further calls.
- A recursive case that reduces the problem toward the base case.
For nonnegative integers, factorial is defined as:
Python implementation:
def factorial(n): if n < 0: raise ValueError("n must be nonnegative") if n == 0: return 1 return n * factorial(n - 1)For
factorial(4), the calls expand as:The base case
n == 0returns1. Without it, calls would continue until Python raised a recursion-depth error. Recursion can express naturally recursive problems clearly, although an iterative solution may use less call-stack memory. -
Question 20 of 20
Explain lambda expressions and distinguish them from functions defined with
def. Also describe the role of docstrings.Model answer
A lambda expression creates a small anonymous function using the syntax
lambda parameters: expression.Example:
square = lambda x: x * x result = square(5)Here,
resultbecomes25.Lambda compared with
def:- A lambda contains only one expression, whose value is returned automatically.
- A function defined with
defcan contain multiple statements, conditionals, loops, annotations, and explicitreturnstatements. - Lambdas are useful for short operations passed to functions such as
sorted(). defis generally preferable for reusable or complex behavior because it supports clearer names and documentation.
Example of a sorting key:
records = [("A", 70), ("B", 60)] records.sort(key=lambda item: item[1])A docstring is a string placed as the first statement in a module, class, or function. It documents purpose, parameters, return values, and important behavior. A function's docstring is available through its
__doc__attribute and tools such ashelp().
That's unit 1
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 1 of ECAP776 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 1 of ECAP776 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.