Quiz#
This quiz covers the key concepts from Lecture 2: Python Fundamentals – Part I, including packages and modules, indentation, Boolean types, operators, numeric types, strings, and control flow.
Note
Instructions:
Answer all questions to the best of your ability.
Multiple choice questions have exactly one correct answer.
True/False questions require you to determine if the statement is correct.
Essay questions require short written responses (2-4 sentences).
Click the dropdown after each question to reveal the answer.
Multiple Choice#
Question 1
What is the difference between a module and a package in Python?
A module is a folder; a package is a single
.pyfile.A module is a single
.pyfile; a package is a folder containing.pyfiles with an__init__.py.A module contains only functions; a package contains only classes.
There is no difference; the terms are interchangeable.
Answer
B – A module is a single .py file; a package is a folder containing .py files with an __init__.py.
A module is any single Python file that can be imported. A package is a directory containing one or more modules plus an __init__.py file (which can be empty) that marks it as a package.
Question 2
Which import approach is recommended for clarity and avoiding namespace pollution?
import shape.squarefrom shape.square import *from shape.square import compute_area, compute_perimeterimport shape.square as s
Answer
C – from shape.square import compute_area, compute_perimeter
This approach explicitly imports only the names you need, making it clear where each function comes from and avoiding namespace pollution. Wildcards (*) can silently overwrite existing names.
Question 3
What is the output of the following code?
print(17 // 5)
print(17 % 5)
3and23.4and23and0.44and2
Answer
A – 3 and 2
17 // 5 is floor division, which returns 3 (the quotient rounded down). 17 % 5 is the modulus operator, which returns 2 (the remainder).
Question 4
Which of the following values is considered truthy in Python?
0""(empty string)[](empty list)" "(string with a single space)
Answer
D – " " (string with a single space)
A string containing a space is non-empty and therefore truthy. Empty containers ([], "") and zero values (0) are falsy.
Question 5
What is the output of the following code?
print(0 or "default")
print("hello" and "world")
0and"hello""default"and"world"FalseandTrue"default"and"hello"
Answer
B – "default" and "world"
The or operator returns the first truthy value ("default" since 0 is falsy). The and operator returns the last value if all are truthy ("world"), or the first falsy value otherwise.
Question 6
What is the correct way to check if a variable x is None?
if x == None:if x is None:if x = None:if x.is_none():
Answer
B – if x is None:
The is operator checks identity (same object in memory). For None, this is the correct approach since there is only one None object in Python. Using == would work but is not idiomatic.
Question 7
Given the string greeting = "hello", what does greeting[-2] return?
"h""o""l""e"
Answer
C – "l"
Negative indices count from the end. greeting[-1] is "o", so greeting[-2] is the second-to-last character, "l".
Question 8
What is the output of "hello"[1:4]?
"hel""ell""ello""hell"
Answer
B – "ell"
Slicing [1:4] extracts characters at indices 1, 2, and 3 (stop index is exclusive). From "hello", these are "e", "l", "l".
Question 9
Which of the following correctly reverses the string "Python" using slicing?
"Python"[::1]"Python"[::-1]"Python"[-1::]"Python"[0:-1:-1]
Answer
B – "Python"[::-1]
A stride of -1 reverses the string. The result is "nohtyP".
Question 10
What is the output of the following code?
x = 5
print(1 < x < 10)
TrueFalseSyntaxError5
Answer
A – True
Python supports chained comparisons. 1 < x < 10 is equivalent to 1 < x and x < 10. Since x = 5, both conditions are true.
Question 11
Why should you avoid comparing floats with ==?
Python does not support float comparisons.
Floats are stored with limited precision, causing rounding errors.
The
==operator only works with integers.Comparing floats raises a
TypeError.
Answer
B – Floats are stored with limited precision, causing rounding errors.
Floating-point numbers use IEEE 754 representation, which cannot exactly represent all decimal values. For example, 0.1 + 0.2 == 0.3 returns False. Use math.isclose() instead.
Question 12
What does the __name__ variable contain when a Python script is run directly?
The filename of the script.
"__main__"NoneThe module’s import path.
Answer
B – "__main__"
When a script is run directly, Python sets its __name__ variable to "__main__". When imported as a module, __name__ is set to the module’s name.
Question 13
Which string formatting method is recommended for Python 3.6+?
"Name: %s" % name"Name: {}".format(name)f"Name: {name}""Name: " + name
Answer
C – f"Name: {name}"
F-strings (formatted string literals) are the recommended approach for Python 3.6+. They are faster, more readable, and support inline expressions.
Question 14
What is the output of the following code?
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
TrueandTrueTrueandFalseFalseandTrueFalseandFalse
Answer
B – True and False
a == b compares values (both lists contain the same elements, so True). a is b compares identity (they are different objects in memory, so False).
Question 15
What is the output of the following code?
score = 75
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)
"A""B""C""F"
Answer
C – "C"
The conditions are evaluated in order. 75 >= 90 is False, 75 >= 80 is False, but 75 >= 70 is True, so grade is assigned "C".
True or False#
Question 16
True or False: Python uses braces {} to define code blocks, similar to C++ and Java.
Answer
False
Python uses indentation (whitespace) to define code blocks, not braces. This is a fundamental difference from C-style languages.
Question 17
True or False: The expression not [] evaluates to True because an empty list is falsy.
Answer
True
An empty list [] is falsy in Python. The not operator inverts the Boolean value, so not [] evaluates to True.
Question 18
True or False: In Python, strings are mutable, meaning you can change individual characters after creation.
Answer
False
Strings in Python are immutable. You cannot change individual characters; instead, you must create a new string. Attempting s[0] = "X" raises a TypeError.
Question 19
True or False: The in operator can be used to check if a substring exists within a string.
Answer
True
The in operator works with strings to check for substrings. For example, "ell" in "hello" returns True.
Question 20
True or False: Python integers have unlimited precision, meaning they can grow arbitrarily large.
Answer
True
Unlike many languages where integers have fixed sizes (32-bit or 64-bit), Python integers can grow to arbitrary size, limited only by available memory.
Question 21
True or False: The expression 10 // -3 evaluates to -3 because floor division rounds toward negative infinity.
Answer
False
10 // -3 evaluates to -4, not -3. Floor division rounds toward negative infinity, so -3.33... rounds down to -4.
Question 22
True or False: Wildcard imports (from module import *) are recommended because they save typing.
Answer
False
Wildcard imports should be avoided because they pollute the namespace and can silently overwrite existing names, making code harder to understand and debug.
Question 23
True or False: The conditional expression status = "adult" if age >= 18 else "minor" is valid Python syntax.
Answer
True
This is Python’s conditional (ternary) expression syntax. It assigns "adult" if the condition is true, otherwise "minor".
Question 24
True or False: Adding a path to sys.path makes packages discoverable for all future Python sessions.
Answer
False
sys.path.insert() only affects the current Python session. The path resets when you start a new Python interpreter. For persistent changes, use PYTHONPATH, .pth files, or pip install -e.
Question 25
True or False: The bool type in Python is a subclass of int, where True equals 1 and False equals 0.
Answer
True
bool is indeed a subclass of int. You can verify this with isinstance(True, int) which returns True. Arithmetic with Booleans is valid: True + True == 2.
Essay Questions#
Question 26
Explain why wildcard imports ( from module import * ) should be avoided. Describe the problem of namespace pollution and provide an example of how it can cause bugs.
(2-4 sentences)
Answer Guidelines
Key points to include:
Wildcard imports (
from module import *) bring all public names from a module into the current namespace.This causes namespace pollution where names from different modules can silently overwrite each other.
Example: If both
shape.squareandshape.circledefinecompute_area(), the second import overwrites the first without warning.Best practice is to use explicit named imports so it’s clear where each function originated.
Question 27
Describe how Python’s short-circuit evaluation works with and and or operators. Explain what values these operators return when used with non-Boolean operands and provide an example use case.
(2-4 sentences)
Answer Guidelines
Key points to include:
andreturns the first falsy value, or the last value if all are truthy.orreturns the first truthy value, or the last value if all are falsy.These operators return the actual operand, not necessarily
TrueorFalse.Common pattern:
name = user_input or "Anonymous"provides a default value whenuser_inputis empty or falsy.
Question 28
Explain the difference between == and is operators. When should you use each one, and why is is recommended for None checks?
(2-4 sentences)
Answer Guidelines
Key points to include:
==compares values (whether two objects have the same content).iscompares identity (whether two references point to the same object in memory).Use
isforNonechecks because there is exactly oneNoneobject in Python, making identity comparison both correct and idiomatic.Never rely on
isfor integers or strings due to interning optimizations that vary by implementation.
Question 29
Describe three methods for making Python packages discoverable (i.e., available for import from anywhere). For each method, explain when it would be most appropriate to use.
(3-5 sentences)
Answer Guidelines
Key points to include:
sys.path.insert(): Adds path for the current script only; good for quick fixes and sibling packages.PYTHONPATHenvironment variable: Affects the terminal session; good for development and testing..pthfiles in site-packages: System-wide and permanent; good for shared libraries across projects.pip install -e .(editable install): Most robust and professional approach; works from anywhere and changes take effect immediately without reinstalling.
Question 30
Explain string slicing syntax [start:stop:stride] and demonstrate how to extract a substring and reverse a string. Use the string "Python" in your examples.
(2-4 sentences)
Answer Guidelines
Key points to include:
Syntax:
[start:stop:stride]where start is inclusive, stop is exclusive, and stride is the step size.Extracting substring:
"Python"[0:2]returns"Py";"Python"[2:]returns"thon".Reversing:
"Python"[::-1]returns"nohtyP"because a stride of-1steps backward through the string.Defaults: start defaults to 0, stop defaults to end, stride defaults to 1.