Unit 1: Setting up your Programming Environment; Variables, Expression and Statements - Subjective Questions
INT108 — Python Programming • Practice Questions with Detailed Answers
20 questions
Explain the significance of Python versions. How can a programmer check the installed Python version?
Python versions represent different releases of the Python language. Python 3 is the current and recommended major version, while Python 2 is obsolete and no longer officially supported.
- New versions introduce features, performance improvements, and security fixes.
- Code written for one version may not work identically in another version.
- The installed version can be checked from a terminal or command prompt using
python --versionorpython3 --version. - It can also be checked within a program using
import sysfollowed byprint(sys.version).
Programmers should confirm the required Python version before installing packages or running a project.
Describe the steps required to install and configure Python on a Windows computer.
Python can be installed and configured on Windows through the following steps:
- Download a current Python 3 installer from the official Python website.
- Run the installer and select Add Python to PATH.
- Choose Install Now or customize the installation when necessary.
- Complete the installation and open Command Prompt or PowerShell.
- Run
python --versionto verify the installation. - Start the interactive interpreter by entering
python. - Optionally verify
pipusingpip --version.
Adding Python to PATH allows commands such as python and pip to be executed from any working directory.
Write a Python program that displays Hello, World! and explain how to save and run it on Windows.
The program is:
print("Hello, World!")
To run it on Windows:
- Open a text editor or Python IDE.
- Enter the program and save it as
hello.py. - Open Command Prompt or PowerShell.
- Use
cdto move to the directory containing the file. - Execute
python hello.py.
The print() function sends the string Hello, World! to standard output. The .py extension identifies the file as a Python source file.
Define a variable in Python. Explain how variables are created, assigned, and updated with suitable examples.
A variable is a name that refers to a value. Python creates a variable when an assignment statement is executed.
age = 18assigns the integer18toage.name = "Ravi"assigns a string toname.age = age + 1reads the current value, adds1, and reassigns the result toage.- A variable may later refer to a value of another type, as in
age = "eighteen".
The = symbol is the assignment operator, not a statement of mathematical equality. The expression on its right is evaluated first, and the resulting value is assigned to the name on its left.
What is a NameError in Python? Explain common situations that cause it and methods for avoiding it.
A NameError occurs when Python tries to use a name that has not been defined in the accessible scope.
Common causes include:
- Using a variable before assigning it, such as
print(total)before definingtotal. - Misspelling a variable name, for example defining
scorebut usingscroe. - Using incorrect capitalization because
Nameandnameare different identifiers. - Referring to a variable outside the scope where it was created.
- Forgetting quotation marks around string text, such as
city = Londoninstead ofcity = "London".
A programmer can avoid this error by initializing variables before use, using consistent spelling and capitalization, quoting string literals, and choosing clear variable names.
Distinguish between a value, a variable, and a data type in Python. Give examples of each.
- A value is an item of data, such as
25,3.5,"Python", orTrue. - A variable is a name that refers to a value, such as
countincount = 25. - A data type classifies a value and determines the operations that can be performed on it.
Examples include:
25has typeint.3.5has typefloat."Python"has typestr.Truehas typebool.
The type of a value can be inspected using type(), for example type(25) returns <class 'int'>. In language = "Python", language is the variable, "Python" is the value, and str is its type.
Explain Python's basic value types and show how type conversion can be performed between compatible types.
Common Python value types include:
int: whole numbers, such as12and-4.float: decimal numbers, such as2.5.str: textual data, such as"42".bool: logical values, namelyTrueandFalse.NoneType: the absence of a value, represented byNone.
Type conversion uses constructor functions:
int("42")produces the integer42.float("3.5")produces the floating-point value3.5.str(100)produces the string"100".bool(0)producesFalse, whilebool(1)producesTrue.
Conversions must be valid. For example, int("hello") raises a ValueError because the text does not represent an integer.
State and explain the rules and recommended conventions for naming variables in Python.
Python variable names must follow these rules:
- A name may contain letters, digits, and underscores.
- It must not begin with a digit.
- It must not contain spaces or symbols such as
-,@, or#. - It must not be a Python keyword.
- Names are case-sensitive, so
total,Total, andTOTALare different.
Recommended conventions include:
- Use descriptive names such as
student_countrather thansc. - Use snake_case for ordinary variable names.
- Avoid replacing built-in names such as
list,str, andsum. - Use uppercase names such as
MAX_SIZEfor values treated as constants.
For example, student_name is valid and clear, while 2name, student-name, and class are invalid.
What are Python keywords? Explain why they cannot be used as variable names and describe how to view the keyword list.
Keywords are reserved words that have predefined grammatical meanings in Python. Examples include if, else, for, while, def, class, return, True, False, and None.
They cannot be used as ordinary variable names because the Python parser uses them to recognize program structure. For example, class = 10 causes a SyntaxError because class begins a class definition.
The current keyword list can be displayed with:
import keyword
print(keyword.kwlist)
The list can vary between Python versions, so the keyword module provides a reliable way to inspect it.
Define a statement in Python. Describe assignment, expression, and output statements using examples.
A statement is an instruction that Python can execute.
- An assignment statement binds a name to a value:
price = 50. - An expression statement evaluates an expression, such as a function call:
len("Python"). - An output statement, commonly implemented as a function call, displays information:
print(price). - A compound statement controls or groups other statements, such as
if price > 0:.
In total = price * 2, Python evaluates the expression price * 2 and then assigns its value to total. Statements usually execute sequentially unless a control-flow statement changes the order.
Differentiate between operators and operands. Classify the major operators available in Python with examples.
An operator is a symbol or keyword that specifies an operation, while an operand is a value on which the operation acts. In 8 + 2, + is the operator and 8 and 2 are operands.
Major operator categories include:
- Arithmetic:
+,-,*,/,//,%, and**. - Comparison:
==,!=,<,>,<=, and>=. - Logical:
and,or, andnot. - Assignment:
=,+=,-=, and similar operators. - Membership:
inandnot in. - Identity:
isandis not.
For example, 17 // 5 gives 3, 17 % 5 gives 2, and 2 ** 3 gives 8.
Explain the difference among /, //, %, and ** in Python. Evaluate each operator using suitable operands.
These arithmetic operators perform different operations:
/performs true division. For example,17 / 5gives3.4.//performs floor division. For example,17 // 5gives3.%returns the remainder. For example,17 % 5gives2.**performs exponentiation. For example,2 ** 4gives16.
Division can be described by:
Therefore, the quotient from floor division is 3 and the remainder is 2. An important detail is that // rounds down toward negative infinity, so -17 // 5 evaluates to -4, not -3.
Explain the order of operations in Python. Evaluate result = 2 + 3 * 4 ** 2 - 8 / 2 step by step.
Python generally follows this precedence order:
- Parentheses
- Exponentiation
- Multiplication, division, floor division, and remainder
- Addition and subtraction
For 2 + 3 * 4 ** 2 - 8 / 2:
- Exponentiation: .
- Multiplication: .
- Division: .
- Addition and subtraction are evaluated from left to right: .
Therefore, result is 46.0. The final value is a float because / produces a floating-point result.
Discuss associativity in Python expressions. Why does exponentiation behave differently from most arithmetic operators?
Associativity determines the evaluation direction when operators have the same precedence.
- Most arithmetic operators of equal precedence are evaluated from left to right. Thus,
20 / 5 * 2becomes(20 / 5) * 2, producing8.0. - Exponentiation is right-associative. Therefore,
2 ** 3 ** 2is interpreted as2 ** (3 ** 2).
Its evaluation is:
By contrast, (2 ** 3) ** 2 gives . Parentheses should be used whenever the intended grouping might be unclear.
Describe the operations that can be performed on strings in Python, including concatenation, repetition, indexing, slicing, and membership testing.
Python supports several useful string operations:
- Concatenation:
"Py" + "thon"produces"Python". - Repetition:
"ha" * 3produces"hahaha". - Indexing:
"Python"[0]produces"P"; negative indexing such as"Python"[-1]produces"n". - Slicing:
"Python"[1:4]produces"yth"because the ending index is excluded. - Membership:
"th" in "Python"producesTrue. - Length:
len("Python")produces6.
Strings are immutable, meaning their individual characters cannot be changed in place. An operation that appears to modify a string actually creates a new string.
Compare arithmetic addition with string concatenation in Python. What errors can occur when incompatible types are combined?
The + operator behaves according to the operand types:
- With numbers, it performs arithmetic addition:
10 + 5gives15. - With strings, it performs concatenation:
"10" + "5"gives"105".
Python does not automatically concatenate a string and an integer. Therefore, "Age: " + 18 raises a TypeError.
The operands must be converted explicitly:
"Age: " + str(18)produces"Age: 18".int("10") + int("5")produces15.
An f-string is often clearer for formatted output: f"Age: {18}". The distinction is important because values that look similar can behave differently when their types differ.
What is composition in programming? Explain how Python combines variables, expressions, and function calls into larger expressions.
Composition means combining smaller expressions and operations to construct a larger computation. The result of one expression can become an operand or function argument in another expression.
For example:
radius = 5
area = 3.14159 * radius ** 2
print("Area:", round(area, 2))
This code composes several elements:
radius ** 2calculates the square.- The result is multiplied by
3.14159. round(area, 2)returns a rounded value.- The rounded value becomes an argument to
print().
Composition makes programs concise, but very long expressions should be divided into well-named intermediate variables when that improves readability.
Develop a Python program that stores a student's name and three marks, calculates the total and average, and displays a formatted result. Explain the role of variables, operators, and composition in the program.
One possible program is:
student_name = "Asha"
mark1 = 78
mark2 = 84
mark3 = 91
total = mark1 + mark2 + mark3
average = total / 3
print(f"Student: {student_name}")
print(f"Total: {total}")
print(f"Average: {average:.2f}")
Explanation:
student_name,mark1,mark2, andmark3store input values.- The
+operator calculates the total. - The
/operator calculates the average using . total / 3composes a variable and an arithmetic operation.- The f-strings compose labels, variables, and formatting instructions.
:.2fdisplays the average with two digits after the decimal point.
Explain the purpose of comments in Python. Distinguish comments from docstrings and state good commenting practices.
A comment is explanatory text ignored by the Python interpreter. A single-line comment begins with #, as in # Calculate the final price. Inline comments may follow code, although they should be used sparingly.
A docstring is a string literal placed at the beginning of a module, class, or function to document its purpose. Unlike a comment, it is available at runtime through tools such as help() and the __doc__ attribute.
Good practices include:
- Explain why a decision was made rather than restating obvious code.
- Keep comments accurate and update them when code changes.
- Use clear variable names so fewer comments are needed.
- Avoid commented-out code in finished programs.
- Use docstrings for public modules, classes, and functions.
Analyze and correct the errors in the following program: class = Python, 2score = 40, total = score + bonus, and print("Total: " + total). Explain every correction.
A corrected version is:
course_name = "Python"
score = 40
bonus = 5
total = score + bonus
print("Total: " + str(total))
Alternatively, the final line can be written as print(f"Total: {total}").
Corrections:
classis a Python keyword, so it is replaced bycourse_name.Pythonmust be enclosed in quotation marks because it is string data.2scoreis invalid because a variable name cannot begin with a digit; it is replaced byscore.bonusmust be assigned before it is used, otherwise aNameErroroccurs.- A string and an integer cannot be joined directly with
+;totalmust be converted withstr()or inserted into an f-string.
The corrected program displays Total: 45.
Explain the significance of Python versions. How can a programmer check the installed Python version?
Python versions represent different releases of the Python language. Python 3 is the current and recommended major version, while Python 2 is obsolete and no longer officially supported.
- New versions introduce features, performance improvements, and security fixes.
- Code written for one version may not work identically in another version.
- The installed version can be checked from a terminal or command prompt using
python --versionorpython3 --version. - It can also be checked within a program using
import sysfollowed byprint(sys.version).
Programmers should confirm the required Python version before installing packages or running a project.
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 →