Unit 1: Python basics - Subjective Questions
ECAP776 • Practice Questions with Detailed Answers
20 questions
Define Python and explain its major features and applications.
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
Explain how a Python program is executed. Distinguish between interactive mode and script mode.
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.
What are identifiers, keywords, variables, and literals in Python? State the rules for naming identifiers.
- 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, and value2. Examples of invalid identifiers include 2value, student-name, and for.
Describe Python's basic built-in data types with suitable examples.
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).
Distinguish between mutable and immutable data types in Python. Explain the distinction using examples.
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.
Explain implicit and explicit type conversion in Python. Illustrate both with examples and mention possible conversion errors.
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.
Classify and explain the operators available in Python with suitable examples.
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.
Explain operator precedence and associativity in Python. Evaluate the expression 2 + 3 * 4 ** 2 // 8 - 1 step by step.
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.
Compare the /, //, %, and ** operators in Python. Explain how floor division and remainder are related.
/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.
Differentiate between equality, identity, and membership operations in Python.
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.
Explain simple if, if-else, and if-elif-else statements in Python. Why is indentation significant?
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, grade becomes "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.
Describe nested conditional statements and logical operators. Write the logic for determining whether a given year is a leap year.
A nested conditional is an if statement 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 by 4 but not by 100. 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.
Explain the while loop in Python. Write and trace a program that calculates the sum of the first natural numbers.
A while loop 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 += 1 is essential; omitting it would create an infinite loop.
Explain the for loop and the range() function. Compare for and while loops with examples of suitable use cases.
A for loop 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) produces 2, 4, 6, 8 during 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 for loop, while repeatedly requesting input until the user enters "quit" suits a while loop.
Describe the purpose of break, continue, and pass in Python. How does the optional else clause of a loop behave?
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, and 4. The value 2 is skipped, and the loop ends when the value becomes 5.
A loop's optional else clause executes when the loop ends normally, including when a for loop exhausts its iterable or a while condition becomes false. It does not execute if the loop is terminated by break. This behavior is useful in searches: the else block can report that no matching item was found.
What is a function in Python? Explain function definition, function call, parameters, arguments, and return values.
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 def keyword:
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 return statement returns None. A return statement also ends that invocation immediately. A function may return multiple comma-separated values; Python packages them into a tuple.
Compare positional, keyword, default, and variable-length arguments in Python functions.
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, details
Calling 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.
Explain local, global, and nonlocal scope in Python using the LEGB name-resolution rule.
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 global statement allows a function to rebind a module-level name.
The nonlocal statement 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 count
Here, inner() modifies the count belonging to outer(), so outer() returns 1.
Excessive use of global state can make programs difficult to test and maintain. Passing values as arguments and returning results is generally clearer.
Define recursion. Explain how a recursive factorial function works, including its base case and recursive case.
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 == 0 returns 1. 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.
Explain lambda expressions and distinguish them from functions defined with def. Also describe the role of docstrings.
A lambda expression creates a small anonymous function using the syntax lambda parameters: expression.
Example:
square = lambda x: x * x
result = square(5)
Here, result becomes 25.
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 as help().
Define Python and explain its major features and applications.
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
Did this save you a night before the exam?
LPU Notes is free, and it stays free. 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. Chip in only if it was worth it. What it pays for →