Unit 1 subjective questions Introduction; Variables, Expressions and Statements
ECE181 — Introduction To Python 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Explain the need for a programming language. Why can't computers be instructed directly in natural human language?
Model answer
A programming language is a formal language comprising a set of instructions used to communicate with a computer and produce various kinds of output.
Need for a programming language:
- Machine understanding: Computers understand only binary (0s and 1s / machine code). Writing directly in machine code is tedious and error-prone. A programming language provides a human-readable way to write instructions that are later translated to machine code.
- Ambiguity of natural language: Human languages like English are ambiguous — the same sentence can have multiple meanings. Computers require precise, unambiguous instructions, which natural language cannot guarantee.
- Abstraction: Programming languages allow programmers to focus on solving problems rather than worrying about low-level hardware details.
- Portability: High-level languages let the same program run on different machines with little or no change.
- Productivity & maintainability: Structured syntax makes code easier to write, read, debug, and maintain.
- Automation: They enable repetitive tasks to be automated efficiently.
Thus, programming languages bridge the gap between human thought and machine execution by offering a precise yet understandable medium.
-
Question 2 of 20
Introduce Python as a programming language. Discuss its key features that make it popular.
Model answer
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability and simplicity.
Key Features:
- Simple and Easy to Learn: Clean, English-like syntax with minimal boilerplate.
- Interpreted: Code is executed line-by-line by the interpreter, making debugging easier.
- Dynamically Typed: Variable types are determined at runtime; no need to declare types explicitly.
- Cross-Platform / Portable: Runs on Windows, Linux, macOS without modification.
- Free and Open Source: Freely available with a large community.
- Extensive Standard Library: Rich set of built-in modules ("batteries included").
- Object-Oriented and Procedural: Supports multiple programming paradigms.
- High-Level: Handles memory management automatically (garbage collection).
- Extensible & Embeddable: Can integrate with C/C++ and other languages.
Applications: Web development, data science, machine learning, automation, scripting, and scientific computing.
Because of these features, Python is widely used by beginners and professionals alike.
-
Question 3 of 20
Describe the different types of programming errors. Explain the process of debugging.
Model answer
Programming errors are mistakes in a program that prevent it from running correctly. They are broadly of three types:
1. Syntax Errors:
- Occur when the rules (grammar) of the language are violated.
- Detected by the interpreter/compiler before execution.
- Example: Missing colon, unbalanced parentheses.
python
if x > 5 # SyntaxError: missing ':'
print(x)
2. Runtime Errors (Exceptions):
- Occur during execution even if syntax is correct.
- Example: Division by zero, accessing undefined variable.
python
print(10 / 0) # ZeroDivisionError
3. Logical Errors:
- Program runs without crashing but produces wrong output.
- Hardest to detect since there is no error message.
- Example: Using
+instead of*in a formula.
Debugging:
Debugging is the systematic process of finding and fixing errors in a program.
- Steps: Reproduce the error → Locate the source → Understand the cause → Fix and test again.
- Techniques: Reading error tracebacks, using
print()statements, using debuggers (likepdb), and testing with sample inputs.
Effective debugging improves program reliability.
-
Question 4 of 20
What are identifiers in Python? State the rules for naming identifiers with examples.
Model answer
An identifier is the name given to entities such as variables, functions, classes, and modules in Python.
Rules for naming identifiers:
- Can contain letters (a–z, A–Z), digits (0–9), and underscore (_).
- Must not begin with a digit. (e.g.,
1nameis invalid,name1is valid) - Cannot be a reserved keyword (e.g.,
if,for,class). - Cannot contain special characters like
@,$,%, or spaces. - Identifiers are case-sensitive (
Ageandageare different). - There is no limit on length.
Valid examples:
python
name = "Alice"
_age = 25
student_1 = True
totalMarks = 90Invalid examples:
python
2var = 5 # starts with a digit
my-name = 3 # contains hyphen
for = 10 # keyword used as identifierGood practice: Use meaningful, descriptive names (e.g.,
total_pricerather thantp). -
Question 5 of 20
Define a variable. Explain how variables are created and used in Python with suitable examples.
Model answer
A variable is a named storage location in memory used to hold data that can be changed during program execution. It acts as a reference (label) to a value.
Creating variables in Python:
- Python variables are created the moment a value is assigned using the
=operator. - No explicit type declaration is needed (dynamic typing).
Pythonx = 10 # integer name = "John" # string pi = 3.14 # float is_valid = True # booleanKey points:
-
A variable refers to an object in memory rather than being a fixed box.
-
The type of a variable is determined by the value assigned.
-
The same variable can be reassigned to a different type:
python
x = 10
x = "hello" # now x refers to a string -
Use the built-in
type()function to check a variable's type:
python
print(type(x)) # <class 'str'>
Variables make programs flexible by allowing values to be stored, reused, and modified.
- Python variables are created the moment a value is assigned using the
-
-
Question 6 of 20
Explain assignment statements in Python. Discuss chained and simultaneous assignment with examples.
Model answer
An assignment statement assigns a value (the result of an expression) to a variable using the assignment operator
=. The value on the right-hand side is evaluated first and then bound to the variable on the left-hand side.Basic assignment:
python
x = 5
y = x + 10Chained assignment: Assigns the same value to multiple variables in one line.
python
a = b = c = 0 # all three become 0Simultaneous (multiple) assignment: Assigns multiple values to multiple variables at once.
python
x, y, z = 1, 2, 3Here
x = 1,y = 2,z = 3.Swapping values using simultaneous assignment (a Python highlight):
python
a, b = 10, 20
a, b = b, a # now a = 20, b = 10Key point: In simultaneous assignment, the right-hand side is fully evaluated before any assignment takes place, which is why swapping works without a temporary variable.
-
Question 7 of 20
What is an expression in Python? Distinguish between an expression and a statement.
Model answer
An expression is a combination of values, variables, operators, and function calls that evaluates to produce a single value.
Examples of expressions:
python
5 + 3 # arithmetic expression -> 8
x * y
(a > b) # boolean expression
len("hello") # function call expression -> 5A statement is a complete instruction that the Python interpreter can execute. It performs an action but may or may not produce a value.
Examples of statements:
python
x = 10 # assignment statement
print(x) # print statement
if x > 5: # conditional statement
passDistinction:
Aspect Expression Statement Definition Evaluates to a value Performs an action Returns value Always Not necessarily Example 2 + 3x = 2 + 3Usage Can be part of a statement Stands as a complete line In short, every expression can be part of a statement, but not every statement is an expression.
-
Question 8 of 20
What is a named constant? How are constants represented in Python? Explain with examples.
Model answer
A named constant is a variable whose value is intended to remain unchanged throughout the program. It gives a meaningful name to a fixed value, improving readability and maintainability.
Representation in Python:
- Python does not have a built-in constant type (unlike C/C++ with
const). - By convention, constants are written in UPPERCASE letters to signal that they should not be modified.
PythonPI = 3.14159 MAX_USERS = 100 GRAVITY = 9.8Usage example:
python
radius = 5
area = PI * radius ** 2
print("Area =", area)Key points:
- The uppercase naming is a coding convention, not enforced by the language — the value can technically still be changed.
- Constants make code self-documenting and reduce the risk of using "magic numbers."
- If a value like
PIis used in many places, changing it in one location (its definition) updates it everywhere.
Using named constants is a best practice for values that logically never change.
- Python does not have a built-in constant type (unlike C/C++ with
-
Question 9 of 20
Describe the numeric data types available in Python with examples.
Model answer
Python provides three built-in numeric data types to represent numbers:
1. Integer (
int):- Represents whole numbers (positive, negative, or zero) without a fractional part.
- Has unlimited precision in Python (limited only by memory).
python
a = 100
b = -45
c = 0
2. Floating-point (
float):- Represents real numbers with a decimal point or in scientific notation.
python
pi = 3.14159
temp = -12.5
large = 2.5e3 # 2500.0
3. Complex (
complex):- Represents numbers with a real and an imaginary part, written as
a + bj.
python
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
Checking type:
python
print(type(100)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(2 + 3j)) # <class 'complex'>Note: The boolean type (
bool) is technically a subtype ofint, whereTrue == 1andFalse == 0. -
Question 10 of 20
Explain the boolean data type in Python. How are boolean values produced and used?
Model answer
The boolean data type (
bool) represents one of two values:TrueorFalse. It is used to represent truth values and is fundamental to decision-making in programs.Key points:
boolis a subclass ofint, soTrueequals1andFalseequals0.
python
print(True + True) # 2
print(False * 10) # 0
Boolean values are produced by:
-
Comparison operators:
==,!=,<,>,<=,>=
python
print(5 > 3) # True
print(2 == 4) # False -
Logical operators:
and,or,not
python
print(True and False) # False
print(not True) # False
Truthiness of values: In boolean contexts, some values are treated as
False:False,0,0.0,""(empty string),None,[],{},()are falsy.- Almost everything else is truthy.
python
if []:
print("won't run") # empty list is falsy
Usage: Boolean values control the flow of programs in
if,while, and other conditional statements. -
Question 11 of 20
Explain the various categories of operators in Python with examples.
Model answer
Operators are special symbols that perform operations on operands (values/variables). Python supports several categories:
1. Arithmetic Operators: Perform mathematical operations.
Operator Meaning Example () Result +Addition a + b13 -Subtraction a - b7 *Multiplication a * b30 /Division a / b3.333 //Floor Division a // b3 %Modulus a % b1 **Exponent a ** b1000 2. Relational (Comparison) Operators:
==,!=,>,<,>=,<=— return boolean values.3. Logical Operators:
and,or,not— combine boolean expressions.4. Assignment Operators:
=,+=,-=,*=, etc.5. Bitwise Operators:
&,|,^,~,<<,>>— operate on binary representations.6. Membership Operators:
in,not in— test membership in sequences.
python
print('a' in 'apple') # True7. Identity Operators:
is,is not— compare object identity.
python
x = [1, 2]; y = x
print(x is y) # True -
Question 12 of 20
Explain operator precedence and associativity in Python. Evaluate the expression step by step.
Model answer
Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first.
Associativity determines the order when operators have the same precedence — most Python operators are left-to-right associative, but
**(exponent) is right-to-left.Precedence (high to low, partial):
()Parentheses**Exponent (right-to-left)+x,-x,~xUnary*,/,//,%+,-- Comparison operators
notandor
Step-by-step evaluation of :
- Step 1 (Exponent): →
3 + 4 * 4 - 6 / 3 - Step 2 (Multiplication): →
3 + 16 - 6 / 3 - Step 3 (Division): →
3 + 16 - 2.0 - Step 4 (Addition): →
19 - 2.0 - Step 5 (Subtraction):
Final Result =
17.0(float, because/always produces a float).Right-associativity example:
2 ** 3 ** 2 = 2 ** (3 ** 2) = 2 ** 9 = 512. -
Question 13 of 20
What are augmented assignment operators? List them and explain their use with examples.
Model answer
Augmented assignment operators combine an arithmetic (or bitwise) operation with assignment in a single, concise operator. They update the value of a variable using its current value.
For example,
x += 5is shorthand forx = x + 5.List of augmented assignment operators:
Operator Equivalent Example () Result +=x = x + yx += 515 -=x = x - yx -= 55 *=x = x * yx *= 220 /=x = x / yx /= 25.0 //=x = x // yx //= 33 %=x = x % yx %= 31 **=x = x ** yx **= 2100 &=,\|=,^=,>>=,<<=Bitwise versions — — Example:
python
count = 0
count += 1 # count = 1
count *= 10 # count = 10
print(count) # 10Advantages:
- Concise and improves readability.
- Reduces repetition of the variable name.
- Commonly used in loops for counters and accumulators.
-
Question 14 of 20
Explain type conversion in Python. Distinguish between implicit and explicit type conversion with examples.
Model answer
Type conversion (type casting) is the process of converting a value from one data type to another.
1. Implicit Type Conversion (Coercion):
- Performed automatically by Python.
- Python converts a smaller/lower data type to a larger/higher one to avoid data loss.
python
a = 5 # int
b = 2.0 # float
c = a + b # int is converted to float automatically
print(c) # 7.0
print(type(c)) # <class 'float'>
2. Explicit Type Conversion (Type Casting):
- Performed manually by the programmer using built-in functions.
- Common functions:
int(),float(),str(),bool(),complex().
python
x = "100"
y = int(x) # string to int -> 100
z = float(y) # int to float -> 100.0
s = str(z) # float to string -> '100.0'
Distinction:
Aspect Implicit Explicit Performed by Python automatically Programmer manually Data loss Avoided Possible (e.g., int(3.9)→ 3)Syntax No function needed Uses conversion functions Note:
int(3.9)gives3(truncates, not rounds). -
Question 15 of 20
Explain the concept of rounding in Python. How does the
round()function work? Discuss with examples.Model answer
Rounding reduces the number of digits in a number while keeping its value close to the original. Python provides the built-in
round()function for this.Syntax:
python
round(number, ndigits)number: the value to round.ndigits: (optional) number of decimal places. If omitted, rounds to the nearest integer.
Examples:
python
print(round(3.14159, 2)) # 3.14
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(7.8)) # 8
print(round(125.66, 1)) # 125.7Banker's Rounding (Round Half to Even):
Python uses banker's rounding, where a value exactly halfway between two integers is rounded to the nearest even number. This reduces cumulative rounding bias.
python
print(round(0.5)) # 0 (nearest even)
print(round(1.5)) # 2
print(round(2.5)) # 2
print(round(3.5)) # 4Related functions (from
mathmodule):math.floor(x)— rounds down to nearest integer.math.ceil(x)— rounds up to nearest integer.math.trunc(x)— removes the decimal part (truncation).
Rounding is important for financial calculations and display formatting.
-
Question 16 of 20
Distinguish between
/(true division),//(floor division), and%(modulus) operators with examples.Model answer
These three operators handle division in different ways:
1. True Division (
/):- Returns the exact quotient as a float, even for whole numbers.
python
print(10 / 3) # 3.3333333333333335
print(10 / 2) # 5.0 (still a float)
2. Floor Division (
//):- Returns the largest integer less than or equal to the quotient (rounds down).
- Result type depends on operands (int if both int, float if any float).
python
print(10 // 3) # 3
print(-10 // 3) # -4 (floors toward negative infinity)
print(10.0 // 3) # 3.0
3. Modulus (
%):- Returns the remainder after division.
python
print(10 % 3) # 1
print(-10 % 3) # 2 (sign follows divisor in Python)
Relationship: For any
aandb:Comparison Table:
Operator Name 10 op 3Type /True division 3.333 float //Floor division 3 int %Modulus 1 int Use case:
%is often used to check even/odd (n % 2 == 0) or to find divisibility. - Returns the exact quotient as a float, even for whole numbers.
-
Question 17 of 20
Explain the logical operators (
and,or,not) in Python and the concept of short-circuit evaluation.Model answer
Logical operators are used to combine or modify boolean expressions and return a boolean (or one of the operands).
1.
andoperator:- Returns
Trueonly if both operands are true.
python
print(True and True) # True
print(True and False) # False
print(5 > 3 and 2 < 4) # True
2.
oroperator:- Returns
Trueif at least one operand is true.
python
print(False or True) # True
print(False or False) # False
3.
notoperator:- Reverses the boolean value.
python
print(not True) # False
print(not 0) # True
Truth Table:
A B A and B A or B T T T T T F F T F T F T F F F F Short-Circuit Evaluation:
Python stops evaluating a logical expression as soon as the result is determined:
- For
and: if the first operand is False, the result isFalse— the second is not evaluated. - For
or: if the first operand is True, the result isTrue— the second is not evaluated.
Pythondef check(): print("called") return True x = False and check() # 'called' is NOT printed y = True or check() # 'called' is NOT printedThis behavior improves efficiency and is often used for safe guards.
- Returns
-
Question 18 of 20
Write short notes on the structure of a Python program and explain how the interpreter processes statements. Include comments and indentation.
Model answer
A Python program is a sequence of statements executed by the Python interpreter in a top-to-bottom manner (unless control flow changes the order).
Key structural elements:
1. Statements: Instructions the interpreter executes.
python
print("Hello") # a statement
x = 5 # assignment statement2. Comments: Non-executable notes for readability.
- Single-line: begin with
#. - Multi-line: enclosed in triple quotes
'''...'''or"""...""".
pythonThis is a single-line comment
"""
This is a
multi-line comment
"""
3. Indentation: Python uses indentation (whitespace) instead of braces
{}to define blocks of code. Consistent indentation is mandatory.
python
if x > 0:
print("Positive") # indented block
print("Number")Incorrect indentation raises an
IndentationError.4. Line continuation: Long statements can span multiple lines using
\or within brackets.
python
total = 1 + 2 + \
3 + 4How the interpreter works:
- Reads source code line by line.
- Translates each statement into bytecode.
- Executes the bytecode on the Python Virtual Machine (PVM).
Because Python is interpreted, errors are reported as the program runs, making it interactive and beginner-friendly.
- Single-line: begin with
-
Question 19 of 20
Given the expressions below, evaluate each and explain the result: (a)
7 // 2 + 3 ** 2, (b)10 % 4 * 2, (c)2 + 3 > 4 and 5 < 2, (d)int("12") + float("3.5").Model answer
Let us evaluate each expression using operator precedence and type rules.
(a)
7 // 2 + 3 ** 2- Exponent first:
3 ** 2 = 9 - Floor division:
7 // 2 = 3 - Addition:
3 + 9 = 12 - Result:
12(int)
(b)
10 % 4 * 2%and*have the same precedence, evaluated left-to-right.- Modulus:
10 % 4 = 2 - Multiplication:
2 * 2 = 4 - Result:
4(int)
(c)
2 + 3 > 4 and 5 < 2- Arithmetic first:
2 + 3 = 5 - Comparisons:
5 > 4→True;5 < 2→False - Logical
and:True and False→False - Result:
False
(d)
int("12") + float("3.5")- Type conversion:
int("12") = 12,float("3.5") = 3.5 - Addition (implicit conversion of int to float):
12 + 3.5 = 15.5 - Result:
15.5(float)
Summary Table:
Expression Result Type (a) 12 int (b) 4 int (c) False bool (d) 15.5 float - Exponent first:
-
Question 20 of 20
Compare compiled and interpreted languages. Explain why Python is called an interpreted language and discuss its advantages and disadvantages.
Model answer
Compiled vs Interpreted Languages:
Aspect Compiled Language Interpreted Language Translation Entire code converted to machine code before execution (by a compiler) Code translated and executed line-by-line (by an interpreter) Execution Speed Generally faster Generally slower Error Detection All errors reported at compile time Errors reported at runtime, one at a time Output Produces a separate executable file No separate executable Examples C, C++, Rust Python, JavaScript, Ruby Why Python is called an interpreted language:
- Python source code (
.py) is first compiled to bytecode (.pyc), which is then executed by the Python Virtual Machine (PVM) line by line. - There is no need to compile the whole program into a machine-code executable beforehand.
Advantages of interpretation in Python:
- Easier debugging: Errors are shown as they occur.
- Platform independence: Bytecode runs on any machine with a Python interpreter.
- Interactive execution: Supports REPL for quick testing.
- Faster development cycle: No separate compilation step.
Disadvantages:
- Slower execution compared to compiled languages.
- Source code is typically required to run the program.
- Higher runtime memory usage.
Despite being slower, Python's simplicity and flexibility make it extremely popular for rapid development.
- Python source code (
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 ECE181 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 1 of ECE181 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.