Unit 1: Basics of Python - Subjective Questions
CAP776 — Programming In Python • 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 uses indentation to organize blocks of code.
Major features:
- Simple syntax: Python programs are easy to read and write.
- Interpreted: Statements are executed by an interpreter without a separate compilation step.
- Dynamically typed: The type of a variable is determined at runtime.
- Portable: Python programs can run on Windows, Linux, and macOS.
- Open source: Python is freely available and supported by a large community.
- Extensive libraries: It provides modules for web development, data analysis, artificial intelligence, automation, and more.
Applications:
- Web and software development
- Data science and visualization
- Machine learning and artificial intelligence
- Scientific computing
- Task automation and scripting
- Education and rapid prototyping
Compare Python IDLE, Jupyter Notebook, and Google Colab as environments for writing and executing Python programs.
Python IDLE:
- Installed with the standard Python distribution.
- Provides an interactive shell and a basic script editor.
- Programs are normally saved as
.pyfiles. - Suitable for beginners and small standalone programs.
Jupyter Notebook:
- Executes code in separate cells.
- Combines executable code, Markdown text, equations, and visualizations.
- Usually runs locally after installing Jupyter.
- Commonly used for data analysis, experimentation, and teaching.
Google Colab:
- A cloud-based notebook environment provided by Google.
- Runs in a web browser and generally requires no local Python installation.
- Stores notebooks in Google Drive and supports easy collaboration.
- Can provide access to hardware accelerators such as GPUs and TPUs.
Key distinction: IDLE is mainly a desktop script-development environment, Jupyter is an interactive notebook environment that usually runs locally, and Colab is a hosted notebook service.
Describe the procedure for creating and running a Python program using IDLE.
The procedure is as follows:
- Open Python IDLE from the operating system's application menu.
- Select File → New File to open the editor.
- Enter the Python program, for example,
print("Hello, Python!"). - Select File → Save or Save As.
- Give the file a meaningful name with the
.pyextension, such ashello.py. - Select Run → Run Module or press F5.
- If necessary, save recent changes when IDLE prompts for confirmation.
- Observe the output in the Python Shell window.
The editor is used to create reusable programs, while the shell displays output and allows individual statements to be tested interactively.
Explain how to create, save, and execute a Python file from both an editor and a command-line interface.
Creating and saving the file:
- Open IDLE, VS Code, or any text editor.
- Write valid Python statements.
- Save the program with the
.pyextension, for example,area.py.
Executing from an editor:
- Use the editor's run command, such as Run Module in IDLE.
- The editor invokes the Python interpreter and displays the output.
Executing from a command line:
- Open Command Prompt, Terminal, or a shell.
- Change to the file's directory using
cd. - Run
python area.pyor, on some systems,python3 area.py.
Important points:
- Python must be installed and available through the system path for command-line execution.
- The file should be saved before it is executed.
- Syntax and runtime errors are displayed by the interpreter and should be corrected before running the program again.
Explain Python's user input and output operations with suitable examples. Why is type conversion often required for input?
Python uses input() to read data and print() to display output.
Input operation:
input()pauses execution and returns the entered data as a string.- A prompt may be supplied:
name = input("Enter your name: ").
Type conversion:
Since input() returns a string, numeric input must usually be converted:
age = int(input("Enter age: "))price = float(input("Enter price: "))
Without conversion, "10" + "20" produces "1020", whereas int("10") + int("20") produces 30.
Output operation:
print(name)displays a value.print("Age:", age)displays multiple values.print(f"Price = {price:.2f}")uses an f-string to format the value to two decimal places.
Useful print() arguments include sep for the separator between values and end for the text printed after the output.
Describe Python's principal numeric data types and illustrate each one with an example.
Python provides three principal built-in numeric data types:
- Integer (
int): Represents whole numbers of arbitrary size. Examples include25,-7, and0. - Floating-point (
float): Represents real numbers using floating-point notation. Examples include3.14,-0.5, and2.0. - Complex (
complex): Represents a number of the form , where is the real part and is the imaginary part. For example,z = 3 + 4j.
The function type() identifies a value's type, such as type(10) returning int. Python may promote an integer during mixed arithmetic; for example, 5 + 2.5 produces the floating-point value 7.5. Complex values provide .real and .imag attributes for accessing their components.
Distinguish between implicit and explicit type conversion in Python. Explain possible errors associated with conversion.
Implicit conversion:
- Performed automatically by Python when compatible numeric types are combined.
- It generally converts a narrower type to a wider type to reduce information loss.
- Example:
5 + 2.5gives7.5; the integer is effectively converted to a float.
Explicit conversion:
- Requested by the programmer through functions such as
int(),float(),str(), andcomplex(). - Examples:
int("25"),float("3.5"), andstr(100).
Possible issues:
int(3.9)produces3, so the fractional part is discarded rather than rounded.int("abc")raises aValueErrorbecause the string is not a valid integer.int("3.5")also raises aValueError; it may first be converted withfloat()if appropriate.- Floating-point values may contain small representation errors.
Input should therefore be validated or conversion should be handled using suitable error-handling techniques.
Classify Python operators and explain each category with examples.
Python operators can be classified as follows:
- Arithmetic:
+,-,*,/,//,%, and**. For example,7 // 2is3, while7 % 2is1. - Comparison:
==,!=,<,>,<=, and>=. They produce Boolean results. - Assignment:
=,+=,-=,*=,/=, and similar operators. For example,x += 2is equivalent tox = x + 2. - Logical:
and,or, andnot. These combine or negate conditions. - Bitwise:
&,|,^,~,<<, and>>. They operate on integer bits. - Membership:
inandnot in. For example,'a' in 'cat'isTrue. - Identity:
isandis not. They test whether two references point to the same object.
The equality operator == compares values, whereas is compares object identity.
Explain operator precedence and associativity in Python. Evaluate the expression 5 + 2 * 3 ** 2 // 3 - 1 step by step.
Operator precedence determines which operator is evaluated first. Associativity determines evaluation order when operators have the same precedence.
For the expression 5 + 2 * 3 ** 2 // 3 - 1:
- Exponentiation has high precedence: .
- Multiplication and floor division are then evaluated from left to right: and .
- Addition and subtraction are evaluated from left to right: .
Therefore, the final result is 10.
A simplified precedence order is:
- Parentheses
- Exponentiation
- Unary operators
- Multiplication, division, floor division, and modulus
- Addition and subtraction
- Comparisons
- Logical
not,and, andor
Parentheses should be used when they improve clarity or force a different evaluation order.
Explain the forms of conditional statements available in Python, including the importance of indentation.
Conditional statements select code based on whether conditions are true or false.
- Simple
if: Executes a block only when its condition is true. if-else: Selects one of two alternative blocks.if-elif-else: Tests several conditions in order; the first true branch executes.- Nested
if: Places one conditional statement inside another.
Example:
if score >= 75:
grade = "A"
elif score >= 60:
grade = "B"
else:
grade = "C"
Python uses indentation rather than braces to identify a block. Statements belonging to the same block must have consistent indentation, conventionally four spaces. Incorrect indentation can cause an IndentationError or change the program's logic.
Develop and explain a Python program that reads marks and displays a grade using the following rules: is A, is B, is C, and below is F. It must reject marks outside .
A suitable program is:
marks = float(input("Enter marks: "))
if marks < 0 or marks > 100:
print("Invalid marks")
elif marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Grade F")
Explanation:
- The input is converted to
floatso that decimal marks can be accepted. - The first condition validates the range.
- The remaining conditions are arranged from the highest boundary to the lowest.
- Once an
iforelifcondition is true, its block executes and the rest of the chain is skipped. - The final
elsehandles all valid marks below .
This ordering prevents a high mark from being classified under a lower grade boundary.
Compare for and while loops in Python. State situations in which each loop is appropriate.
for loop:
- Iterates over the elements of an iterable such as a string, list, or
rangeobject. - It is suitable when the items or approximate number of iterations are known.
- Example:
for i in range(1, 6): print(i).
while loop:
- Repeats while a Boolean condition remains true.
- It is suitable when the number of iterations depends on user input or a changing condition.
- Example:
while balance > 0: ....
Differences:
- A
forloop advances through an iterable automatically. - A
whileloop normally requires explicit initialization and updating of control variables. - A poorly designed
whilecondition may create an infinite loop.
Both loops may contain an optional else block, which executes after normal completion but not when the loop terminates through break.
Explain the range() function and determine the values generated by range(5), range(2, 8), and range(10, 2, -2).
range() creates an immutable sequence of integers and is commonly used with for loops.
Its general form is range(start, stop, step):
startis included and defaults to0.stopis excluded.stepdefaults to1and cannot be zero.
Generated values:
range(5)gives0, 1, 2, 3, 4.range(2, 8)gives2, 3, 4, 5, 6, 7.range(10, 2, -2)gives10, 8, 6, 4.
The last sequence uses a negative step, so it decreases. The value 2 is not included because the stopping boundary is always exclusive. To display the complete sequence directly, it can be converted using list(range(...)).
Write and explain a sentinel-controlled while loop that repeatedly reads numbers and calculates their sum until the user enters 0.
A sentinel is a special value used to terminate repetition. Here, 0 is the sentinel.
total = 0
number = float(input("Enter a number, or 0 to stop: "))
while number != 0:
total += number
number = float(input("Enter a number, or 0 to stop: "))
print("Sum =", total)
Explanation:
totalis initialized to zero before the loop.- The first number is read before testing the condition.
- While the number is not the sentinel, it is added to
total. - A new value must be read inside the loop; otherwise, the condition never changes.
- When
0is entered, the loop ends and the accumulated sum is displayed. - The sentinel itself is not included in the calculation.
Differentiate among break, continue, and pass in Python, with suitable loop-related examples.
break: Immediately terminates the nearest enclosing loop. For example,if value < 0: breakcan stop processing when a negative value is encountered.continue: Skips the remaining statements in the current iteration and proceeds to the next iteration. For example,if value == 0: continuecan ignore zero values.pass: Performs no operation. It is used as a syntactic placeholder where Python requires a statement.
Example:
for number in range(-2, 4):
if number < 0:
pass
if number == 0:
continue
if number == 3:
break
print(number)
Here, pass does not alter execution, continue prevents zero from being printed, and break ends the loop when the value becomes 3. These statements should be used carefully because excessive use can make loop logic difficult to follow.
Describe nested loops and write a Python program to display the following pattern for : 1, 12, 123, 1234 on separate lines.
A nested loop is a loop placed inside another loop. For every iteration of the outer loop, the inner loop completes all of its required iterations.
Program:
n = 4
for row in range(1, n + 1):
for number in range(1, row + 1):
print(number, end="")
print()
Output:
1
12
123
1234
Explanation:
- The outer loop controls the row number from
1to4. - For each row, the inner loop prints values from
1through the current row number. end=""preventsprint()from moving to a new line after each number.- The empty
print()after the inner loop moves output to the next line.
Nested loops are also used for tables, matrices, and comparing combinations of values.
Define a user-defined function in Python. Explain its syntax, function call, parameters, and return value.
A user-defined function is a named, reusable block of code created by the programmer to perform a specific task.
General syntax:
def function_name(parameters):
"""Optional documentation string."""
statements
return value
Example:
def square(number):
return number ** 2
result = square(5)
Explanation:
defbegins the function definition.squareis the function name.numberis a formal parameter.square(5)is the function call, and5is the argument.returnsends the calculated result back to the caller.- If no explicit
returnis executed, the function returnsNone.
Functions support modularity, code reuse, testing, and clearer program organization.
Explain positional, keyword, and default arguments in Python functions. Also distinguish between local and global variables.
Argument types:
- Positional arguments: Matched to parameters according to their order, as in
power(2, 3). - Keyword arguments: Matched by parameter name, as in
power(exponent=3, base=2). - Default arguments: Use predefined values when the caller omits them, as in
def power(base, exponent=2): ....
Parameters without default values must normally appear before parameters with default values.
Variable scope:
- A local variable is created inside a function and is normally accessible only within that function.
- A global variable is defined outside functions and can generally be read throughout the module.
- Assigning to a global variable inside a function requires the
globaldeclaration.
It is usually better to pass values as arguments and return results rather than modifying global variables, because this reduces hidden dependencies and makes functions easier to test.
Develop a user-defined function to calculate the factorial of a non-negative integer. Explain the algorithm and show how invalid input can be handled.
For a non-negative integer , factorial is defined as:
Also, .
Program:
def factorial(n):
if n < 0:
raise ValueError("Factorial is undefined for negative integers")
result = 1
for value in range(2, n + 1):
result *= value
return result
number = int(input("Enter a non-negative integer: "))
try:
print("Factorial =", factorial(number))
except ValueError as error:
print(error)
Algorithm:
- Reject a negative argument.
- Initialize
resultto1. - Multiply
resultby every integer from2through . - Return the final product.
The loop does not execute for or , so the function correctly returns 1 in both cases.
Design a Python program using input/output, a loop, conditional statements, and user-defined functions to read numbers and report their sum, average, largest value, and count of even integers.
One possible solution is:
def analyze_numbers(count):
total = 0
largest = None
even_count = 0
for index in range(count):
number = int(input(f"Enter number {index + 1}: "))
total += number
if largest is None or number > largest:
largest = number
if number % 2 == 0:
even_count += 1
average = total / count
return total, average, largest, even_count
n = int(input("How many numbers? "))
if n <= 0:
print("The count must be positive.")
else:
total, average, largest, even_count = analyze_numbers(n)
print("Sum =", total)
print(f"Average = {average:.2f}")
print("Largest =", largest)
print("Even count =", even_count)
Explanation:
- The main conditional validates that .
- The
forloop reads exactly integers. - An accumulator calculates the sum.
largestis initialized withNoneso the first entered value can establish the initial maximum.- The condition
number % 2 == 0identifies even integers. - The average is calculated as .
- The function returns four results, which are unpacked and displayed by the caller.
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 uses indentation to organize blocks of code.
Major features:
- Simple syntax: Python programs are easy to read and write.
- Interpreted: Statements are executed by an interpreter without a separate compilation step.
- Dynamically typed: The type of a variable is determined at runtime.
- Portable: Python programs can run on Windows, Linux, and macOS.
- Open source: Python is freely available and supported by a large community.
- Extensive libraries: It provides modules for web development, data analysis, artificial intelligence, automation, and more.
Applications:
- Web and software development
- Data science and visualization
- Machine learning and artificial intelligence
- Scientific computing
- Task automation and scripting
- Education and rapid prototyping
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 →