Unit 1 subjective questions Setting up your Programming Environment; Variables, Expression and Statements
INT108 — Python Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Explain the significance of Python versions. How can a programmer check the installed Python version?
Model answer
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.
-
Question 2 of 20
Describe the steps required to install and configure Python on a Windows computer.
Model answer
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
PATHallows commands such aspythonandpipto be executed from any working directory. -
Question 3 of 20
Write a Python program that displays
Hello, World!and explain how to save and run it on Windows.Model answer
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 stringHello, World!to standard output. The.pyextension identifies the file as a Python source file. -
Question 4 of 20
Define a variable in Python. Explain how variables are created, assigned, and updated with suitable examples.
Model answer
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. -
Question 5 of 20
What is a
NameErrorin Python? Explain common situations that cause it and methods for avoiding it.Model answer
A
NameErroroccurs 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.
- Using a variable before assigning it, such as
-
-
Question 6 of 20
Distinguish between a value, a variable, and a data type in Python. Give examples of each.
Model answer
- 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 exampletype(25)returns<class 'int'>. Inlanguage = "Python",languageis the variable,"Python"is the value, andstris its type. - A value is an item of data, such as
-
Question 7 of 20
Explain Python's basic value types and show how type conversion can be performed between compatible types.
Model answer
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 aValueErrorbecause the text does not represent an integer. -
Question 8 of 20
State and explain the rules and recommended conventions for naming variables in Python.
Model answer
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_nameis valid and clear, while2name,student-name, andclassare invalid. -
Question 9 of 20
What are Python keywords? Explain why they cannot be used as variable names and describe how to view the keyword list.
Model answer
Keywords are reserved words that have predefined grammatical meanings in Python. Examples include
if,else,for,while,def,class,return,True,False, andNone.They cannot be used as ordinary variable names because the Python parser uses them to recognize program structure. For example,
class = 10causes aSyntaxErrorbecauseclassbegins 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
keywordmodule provides a reliable way to inspect it. -
Question 10 of 20
Define a statement in Python. Describe assignment, expression, and output statements using examples.
Model answer
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 expressionprice * 2and then assigns its value tototal. Statements usually execute sequentially unless a control-flow statement changes the order. - An assignment statement binds a name to a value:
-
Question 11 of 20
Differentiate between operators and operands. Classify the major operators available in Python with examples.
Model answer
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 and8and2are 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 // 5gives3,17 % 5gives2, and2 ** 3gives8. - Arithmetic:
-
Question 12 of 20
Explain the difference among
/,//,%, and**in Python. Evaluate each operator using suitable operands.Model answer
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
3and the remainder is2. An important detail is that//rounds down toward negative infinity, so-17 // 5evaluates to-4, not-3. -
Question 13 of 20
Explain the order of operations in Python. Evaluate
result = 2 + 3 * 4 ** 2 - 8 / 2step by step.Model answer
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,
resultis46.0. The final value is a float because/produces a floating-point result. -
Question 14 of 20
Discuss associativity in Python expressions. Why does exponentiation behave differently from most arithmetic operators?
Model answer
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) ** 2gives . Parentheses should be used whenever the intended grouping might be unclear. - Most arithmetic operators of equal precedence are evaluated from left to right. Thus,
-
Question 15 of 20
Describe the operations that can be performed on strings in Python, including concatenation, repetition, indexing, slicing, and membership testing.
Model answer
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.
- Concatenation:
-
Question 16 of 20
Compare arithmetic addition with string concatenation in Python. What errors can occur when incompatible types are combined?
Model answer
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: " + 18raises aTypeError.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. - With numbers, it performs arithmetic addition:
-
Question 17 of 20
What is composition in programming? Explain how Python combines variables, expressions, and function calls into larger expressions.
Model answer
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.
-
Question 18 of 20
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.
Model answer
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.
-
Question 19 of 20
Explain the purpose of comments in Python. Distinguish comments from docstrings and state good commenting practices.
Model answer
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.
-
Question 20 of 20
Analyze and correct the errors in the following program:
class = Python,2score = 40,total = score + bonus, andprint("Total: " + total). Explain every correction.Model answer
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.
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 INT108 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 1 of INT108 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.