INT108 viva questions Python Programming
60 questions across 6 units, with answers. Say your answer out loud first, then check it.
-
Question 1 of 60Unit 1, Python VersionsEasy
What is the primary difference between Python 2 and Python 3 mentioned in the syllabus regarding backward compatibility?
Answer
Python 3 is the current standard and is not backward compatible with Python 2. This means code written for Python 2 may not run on a Python 3 interpreter without modification. Significant differences include how print statements work (parentheses are required in Python 3) and how integer division is handled.
-
Question 2 of 60Unit 1, Environment SetupMedium
Why is it critical to check 'Add Python to PATH' during installation on Windows?
Answer
Checking 'Add Python to PATH' allows you to run Python from the Command Prompt (cmd) or terminal using the simple
pythoncommand from any directory. Without this, the operating system will not know where the Python executable is located, and you would have to type the full file path to run scripts. -
Question 3 of 60Unit 1, VariablesEasy
Explain the concept of Dynamic Typing in Python.
Answer
Dynamic Typing means that you do not need to declare the data type (like
intorchar) of a variable before using it. Python infers the type based on the value assigned. For example,x = 10makesxan integer, andx = 'Hello'makes it a string automatically. -
Question 4 of 60Unit 1, Variable NamingEasy
List three rules for naming variables in Python.
Answer
- Variable names must start with a letter (a-z, A-Z) or an underscore (
_); they cannot start with a number. - They can contain alphanumeric characters and underscores.
- They are case-sensitive (e.g.,
myVarandMyVarare different). - You cannot use Python keywords (reserved words like
if,class,def) as variable names.
- Variable names must start with a letter (a-z, A-Z) or an underscore (
-
Question 5 of 60Unit 1, OperatorsMedium
What is the difference between the
/operator and the//operator?Answer
The
/operator performs standard division and always returns a float, even if the result is a whole number (e.g.,10 / 2returns5.0). The//operator performs Floor Division, which divides the numbers and rounds the result down to the nearest whole number (e.g.,10 // 3returns3). -
-
Question 6 of 60Unit 1, String OperationsMedium
How does the
*operator function when applied to a string?Answer
When the
*operator is used with a string and an integer, it performs repetition. It repeats the string the specified number of times. For example,'Spam' * 3results in the string'SpamSpamSpam'. -
Question 7 of 60Unit 1, ErrorsEasy
What causes a
NameErrorin Python?Answer
A
NameErroroccurs when the code tries to use a variable that has not yet been defined (assigned a value). This often happens due to misspellings (e.g., typingmesageinstead ofmessage) or trying to print a variable before the line of code where it is assigned. -
Question 8 of 60Unit 1, Order of OperationsMedium
Explain the PEMDAS rule in Python expression evaluation.
Answer
PEMDAS stands for the order of precedence in mathematical operations:
- Parentheses
() - Exponents
** - Multiplication
*and Division/,//,%(evaluated left-to-right) - Addition
+and Subtraction-(evaluated left-to-right).
- Parentheses
-
Question 9 of 60Unit 1, CompositionHard
What is 'Composition' in the context of Python statements?
Answer
Composition is the ability to combine simple expressions and statements into compound ones. It allows you to use the result of one expression directly as part of another, such as nesting functions (e.g.,
print(type(x))) or performing arithmetic inside a function call (e.g.,print(10 * 5)). -
Question 10 of 60Unit 1, CommentsEasy
How do you denote a single-line comment versus a multi-line comment in Python?
Answer
A single-line comment starts with the hash character (
#). Python ignores everything after the#on that line. While Python doesn't have specific multi-line comment syntax, programmers often use triple quotes ('''or""")—technically multi-line strings/docstrings—or multiple lines starting with#to create multi-line comments. -
Question 11 of 60Unit 2, The Modulus OperatorMedium
What are two common use cases for the Modulus operator (
%)?Answer
- Checking Parity: Determining if a number is even (
x % 2 == 0) or odd. - Extracting Digits: Getting the right-most digit of a number (e.g.,
123 % 10returns3). - Cyclic Operations: Wrapping values around, such as in clock arithmetic.
- Checking Parity: Determining if a number is even (
-
Question 12 of 60Unit 2, Random NumbersEasy
What does
random.random()return compared torandom.randint(a, b)?Answer
random.random()returns a floating-point number between0.0(inclusive) and1.0(exclusive).random.randint(a, b)returns a random integer such that (inclusive of both endpoints). -
Question 13 of 60Unit 2, Logic OperatorsHard
Explain 'Short-circuit evaluation' in Python logical operators.
Answer
Short-circuit evaluation means Python stops evaluating a boolean expression as soon as the result is determined.
- For
and: If the first operand isFalse, Python stops (result is False). - For
or: If the first operand isTrue, Python stops (result is True).
This saves processing time and can prevent errors in the second part of the expression.
- For
-
Question 14 of 60Unit 2, Boolean ExpressionsEasy
What is the difference between
=and==?Answer
=is the assignment operator used to assign a value to a variable (e.g.,x = 5).==is the relational (equality) operator used to compare two values, returningTrueif they are equal andFalseotherwise. -
Question 15 of 60Unit 2, Conditional StatementsMedium
When would you use
elifinstead of a nestedelse: ifstructure?Answer
elif(chained conditionals) is used when there are more than two possibilities. It makes the code cleaner and flatter (easier to read) than deeply nestedif...elsestructures. Only the first branch with a True condition executes. -
Question 16 of 60Unit 2, While LoopsMedium
Why is a
whileloop called 'indefinite iteration'?Answer
It is called indefinite because the number of times the loop will execute is not necessarily known before the loop starts. It continues to run as long as a specific condition remains
True, unlike aforloop which iterates over a fixed sequence. -
Question 17 of 60Unit 2, Loop ControlMedium
Differentiate between
breakandcontinue.Answer
breakterminates the loop immediately, jumping to the code following the loop.continueskips the rest of the code in the current iteration and jumps back to the top of the loop to check the condition again. -
Question 18 of 60Unit 2, For LoopsMedium
What sequence does
range(2, 10, 2)generate?Answer
It generates the sequence:
2, 4, 6, 8.
It starts at2, stops before10(exclusive), and increments by2(step value). -
Question 19 of 60Unit 2, EncapsulationHard
How does Encapsulation improve code quality in the context of loops?
Answer
Encapsulation involves wrapping a piece of code (like a loop) into a function. This isolates the logic, allows you to name the process (e.g.,
draw_square()), and makes the main program cleaner and easier to read. -
Question 20 of 60Unit 2, GeneralizationHard
What is Generalization in programming functions?
Answer
Generalization is the process of taking encapsulated code and making it versatile by replacing specific literal values (like
100or4) with variables (parameters). This allows the same function to solve a wider range of scenarios (e.g., drawing a square of any size, not just size 100). -
Question 21 of 60Unit 3, Function TypesEasy
What is the difference between a Fruitful function and a Void function?
Answer
Fruitful functions return a result that can be assigned to a variable or used in an expression (e.g.,
len()). Void functions perform an action (likeprint()) but do not return a meaningful value; technically, they return the special valueNone. -
Question 22 of 60Unit 3, Type ConversionMedium
Explain the difference between Type Coercion and Type Casting.
Answer
Type Coercion (Implicit) happens automatically when Python converts data types to prevent data loss (e.g., adding an
intto afloatresults in afloat). Type Casting (Explicit) is when the programmer manually converts types using functions likeint(),float(), orstr(). -
Question 23 of 60Unit 3, Math FunctionsEasy
What does
math.ceil(4.2)return and why?Answer
It returns
5. Themath.ceil(x)function returns the smallest integer greater than or equal tox. Essentially, it always rounds up. -
Question 24 of 60Unit 3, Variable ScopeMedium
What is the scope of a 'Local Variable'?
Answer
A local variable is defined inside a function. It exists only while the function is executing and is destroyed when the function exits. It cannot be accessed from outside that specific function.
-
Question 25 of 60Unit 3, Parameters vs ArgumentsMedium
Technically, how do Parameters differ from Arguments?
Answer
Parameters are the variables listed inside the parentheses in the function definition (the placeholders). Arguments are the actual values sent to the function when it is called (the data).
-
Question 26 of 60Unit 3, Argument TypesMedium
How do Keyword Arguments differ from Positional Arguments?
Answer
Positional arguments must be passed in the correct order defined by the function. Keyword arguments are passed with
key=valuesyntax, meaning the order does not matter (e.g.,func(b=5, a=10)). -
Question 27 of 60Unit 3, Arbitrary ArgumentsHard
When would you use
*argsin a function definition?Answer
You use
*argswhen you do not know beforehand how many arguments will be passed to the function. It allows the function to receive a tuple of arguments, which can then be iterated over. -
Question 28 of 60Unit 3, RecursionHard
What are the two mandatory parts of a recursive function to avoid infinite loops?
Answer
- Base Case: A condition where the function returns a value without making a recursive call (stopping condition).
- Recursive Case: The part where the function calls itself with a modified argument that moves closer to the base case.
-
Question 29 of 60Unit 3, Recursion MemoryHard
What is a limitation of using recursion regarding memory?
Answer
Recursion is memory-intensive because every recursive call creates a new "stack frame" on the memory stack. If there are too many calls (deep recursion), it can lead to a
RecursionError: maximum recursion depth exceeded. -
Question 30 of 60Unit 3, Flow of ExecutionMedium
Describe the flow of execution when a function is called.
Answer
- The program pauses execution at the call point.
- Control transfers to the first line of the called function.
- The function body executes.
- Upon completion (or hitting
return), control returns to the caller, resuming exactly where it left off.
-
Question 31 of 60Unit 4, String ImmutabilityMedium
What does it mean that strings are 'immutable' in Python?
Answer
It means that once a string is created, its elements (characters) cannot be changed in place. You cannot do
str[0] = 'a'. To change a string, you must create a new string with the desired changes. -
Question 32 of 60Unit 4, SlicingMedium
In the slice
s[start:stop], is thestopindex inclusive or exclusive?Answer
The
stopindex is exclusive. The slice includes characters fromstartup to, but not including,stop. -
Question 33 of 60Unit 4, Lists vs TuplesEasy
What is the primary difference between a List and a Tuple?
Answer
Lists are mutable (can be changed after creation) and use square brackets
[]. Tuples are immutable (cannot be changed) and use parentheses(). -
Question 34 of 60Unit 4, List DeletionMedium
How does
pop()differ fromremove()in lists?Answer
pop(index)removes an element by its index and returns the value.remove(value)removes the first occurrence of a specific value and does not return it. -
Question 35 of 60Unit 4, Tuple AssignmentMedium
How can you swap values of two variables
aandbusing tuple assignment?Answer
You can swap them in one line using:
a, b = b, a. This implies simultaneous assignment where the right side is packed into a tuple and unpacked into the variables on the left. -
Question 36 of 60Unit 4, Dictionary BasicsEasy
What are the requirements for keys in a Python dictionary?
Answer
Dictionary keys must be unique and immutable types (like strings, numbers, or tuples). Mutable types like lists cannot be used as keys.
-
Question 37 of 60Unit 4, Dictionary MethodsMedium
Why would you use the
get()method instead of bracket notationdict[key]?Answer
Using
dict[key]raises aKeyErrorif the key does not exist. Theget(key, default)method prevents this error by returning a specific default value (or None) if the key is missing. -
Question 38 of 60Unit 4, Sparse MatricesHard
How can dictionaries be used to represent sparse matrices efficiently?
Answer
Instead of storing a list of lists with many zeros, a dictionary stores only the non-zero elements. The keys are tuples representing coordinates
(row, col), and the values are the data.matrix_dict.get((r,c), 0)allows retrieving values, defaulting to 0 for missing keys. -
Question 39 of 60Unit 4, AliasingHard
What is Aliasing in the context of lists?
Answer
Aliasing occurs when two variables refer to the exact same object in memory (e.g.,
b = a). Since lists are mutable, changes made via one variable (alias) will be reflected in the other. -
Question 40 of 60Unit 4, CopyingHard
What is the difference between a Shallow Copy and a Deep Copy?
Answer
A Shallow Copy (e.g.,
a[:]) copies the list structure but references the same inner objects if nested. A Deep Copy (copy.deepcopy()) recursively copies the list and all nested objects, ensuring total independence between the original and the copy. -
Question 41 of 60Unit 5, OOP ConceptsEasy
Define 'Class' and 'Object'.
Answer
A Class is a blueprint or prototype that defines attributes and methods. An Object is a unique instance of that class containing actual data.
-
Question 42 of 60Unit 5, ConstructorsMedium
What is the purpose of the
__init__method?Answer
__init__is the constructor method. It is automatically called when a new instance of a class is created and is used to initialize the object's attributes (state). -
Question 43 of 60Unit 5, The self ParameterMedium
What does
selfrepresent in a Python class method?Answer
selfrepresents the specific instance of the class currently being manipulated. It allows access to the attributes and methods of that specific object. -
Question 44 of 60Unit 5, InheritanceEasy
What is Class Inheritance?
Answer
Inheritance allows a class (Child/Derived) to acquire the methods and properties of another class (Parent/Base). It promotes code reusability.
-
Question 45 of 60Unit 5, Method OverridingMedium
What is Method Overriding?
Answer
Method overriding occurs when a child class provides a specific implementation for a method that is already defined in its parent class. The method name remains the same.
-
Question 46 of 60Unit 5, Super FunctionHard
What is the use of the
super()function in inheritance?Answer
super()returns a temporary object of the superclass (parent), allowing the child class to call methods from the parent. This is often used when overriding a method to extend its functionality rather than replacing it entirely. -
Question 47 of 60Unit 5, EncapsulationMedium
How do you denote a 'Private' attribute in Python, and what does it do?
Answer
A private attribute is denoted by double underscores
__prefix (e.g.,self.__balance). Python uses name mangling to make these harder to access from outside the class, enforcing data hiding. -
Question 48 of 60Unit 5, Name ManglingHard
Can private attributes be accessed at all? If so, how?
Answer
Yes, technically they can. Python changes the name internally (Name Mangling) to
_ClassName__variableName. You can access it using this mangled name, though it is not recommended. -
Question 49 of 60Unit 5, Function OverloadingMedium
Does Python support traditional function overloading? How is it handled?
Answer
Python does not support traditional function overloading (multiple methods with the same name but different parameters). If you define two, the last one overwrites the first. Instead, overloading is simulated using default arguments (
None) or variable-length arguments (*args). -
Question 50 of 60Unit 5, AttributesEasy
What is the difference between Class Attributes and Instance Attributes?
Answer
Class Attributes are shared by all instances of the class. Instance Attributes (defined in
__init__usingself) are unique to each specific object. -
Question 51 of 60Unit 6, File ModesEasy
What is the difference between 'w' and 'a' modes in file handling?
Answer
'w'(Write) opens a file for writing but truncates (deletes) existing content or creates a new file.'a'(Append) opens a file for writing but places the pointer at the end, preserving existing content. -
Question 52 of 60Unit 6, Context ManagersMedium
Why is it best practice to use the
withstatement when opening files?Answer
The
withstatement automatically handles resource management. It ensures the file is closed automatically after the block is executed, even if an exception/error occurs within the block. -
Question 53 of 60Unit 6, Reading FilesMedium
What is the difference between
read()andreadlines()?Answer
read()reads the entire file as a single string.readlines()reads the entire file and returns a list of strings, where each string is a line from the file. -
Question 54 of 60Unit 6, Writing FilesEasy
Can you pass an integer directly to the
file.write()method?Answer
No,
write()only accepts strings. You must convert integers or other types to strings (usingstr()or f-strings) before writing them to a text file. -
Question 55 of 60Unit 6, SerializationHard
What is 'Pickling' in Python?
Answer
Pickling is the process of serializing a Python object hierarchy (like a dictionary or list) into a byte stream. This allows complex data structures to be saved to a file using the
picklemodule. -
Question 56 of 60Unit 6, Exception HandlingMedium
What is the purpose of the
try...exceptblock?Answer
It is used to handle runtime errors (exceptions) without crashing the program. Code that might fail goes in
try; if an error occurs, the code inexceptruns to handle the error gracefully. -
Question 57 of 60Unit 6, The Else BlockMedium
When does the
elseblock execute in atry...except...elsestructure?Answer
The
elseblock executes only if no exceptions were raised in thetryblock. It separates the code that might fail from the code that should run only upon success. -
Question 58 of 60Unit 6, Regular ExpressionsEasy
What do the metacharacters
.and^represent in Regex?Answer
.matches any single character (except newline).^asserts the start of a string (matches only at the beginning). -
Question 59 of 60Unit 6, Regex FunctionsMedium
How does
re.match()differ fromre.findall()?Answer
re.match()checks for a match only at the beginning of the string.re.findall()scans the entire string and returns a list of all non-overlapping matches. -
Question 60 of 60Unit 6, Regex Special SequencesMedium
What do
\dand\wmatch in a Regular Expression?Answer
\dmatches any digit (0-9).\wmatches any alphanumeric character (letters a-z, numbers 0-9, and underscore).
That's the set
Go back over the ones you couldn't answer without looking. The unit notes cover each topic in full.
Nearly through. Did viva questions for INT108 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did viva questions for 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.