Midterm Review: Python Problem Sets 3
Problem 1: Assignment Expression Syntax
Is there a difference between these two lines of code? Would they result in an runtime error?
x = (a = 5)x = a = 5Solution
Yes, there is a significant difference.
First line: x = (a = 5) → SyntaxError: invalid syntax. This is a syntax error because the = operator (assignment) cannot be used inside parentheses without the walrus operator :=. Standard assignment = is a statement, not an expression.
Second line: x = a = 5 → Valid. This is chained assignment. Both x and a are assigned the value 5.
Explanation: The first line would need to use the walrus operator to work: x = (a := 5), which assigns 5 to a and then assigns that value to x.
Problem 2: Walrus Operator and Assignment
What is the final value of a?
print(a := 10)
a = 20
print(a := a + 5)Solution
Output:
10
25
The value of a after all statements is 25.
Explanation:
print(a := 10)uses the walrus operator to assign 10 toaand print it, outputting 10.a = 20reassignsato 20.print(a := a + 5)uses the walrus operator to assigna + 5(which is 25) toaand prints it, outputting 25.
So the final value of a is 25.
Problem 3: Walrus Operator in Print statement
What is the output of this code? Explain the difference between the two approaches. Any errors?
# Approach 1
print(a = 7)
# Approach 2
print(a := 7)Solution
Approach 1: print(a = 7) → SyntaxError: invalid syntax. This is invalid because = is used for assignment, which is a statement, not an expression. It cannot be used as an argument to a function.
Approach 2: print(a := 7) → Output: 7. This works correctly. The walrus operator := is an assignment expression that assigns 7 to a and also returns the value 7, which is then printed. The variable a is created with the value 7.
Explanation: The key difference is that := (walrus operator) is an expression that returns a value, while = is only a statement that doesn’t return a value.
Problem 4: While Loop with Assignment
Identify and fix the error in this code. Can you fix this by adding just one more character?
while input_str = input("Enter text: "):
print(input_str)Solution
Error: The = operator in the while condition is invalid. Assignment statements cannot be used in conditions.
Fix: Replace = with := (the walrus operator) to make it an assignment expression:
while input_str := input("Enter text: "):
print(input_str)Explanation: The walrus operator := assigns the input to input_str and returns that value. The loop continues as long as the input is truthy (non-empty strings). An empty string will cause the loop to exit.
Problem 5: Floor Division vs Int Conversion
Explain the difference between the // operator and int for division truncation.
>>> 2.9 // 1
>>> int(2.9 / 1)
>>> -2.9 // 1
>>> int(-2.9 / 1)Solution
Output:
2.0
2
-3.0
-2
Explanation: The key difference is in how they handle negative numbers:
//is floor division: it rounds towards negative infinity.int()truncates towards zero.
For positive numbers, they behave the same way:
2.9 // 1 = 2.0(floor division rounds down)int(2.9 / 1) = 2(truncates towards zero)
For negative numbers, they differ:
-2.9 // 1 = -3.0(floor division rounds down to -3)int(-2.9 / 1) = -2(truncates towards zero to -2)
Also note that // returns a float when one operand is a float, while int() always returns an integer.
Problem 6: Boolean Type Conversions
Explain the output of these expressions:
print(bool('False'))
print(bool(''))
print(bool(0.0))
print(bool([]))Solution
Output:
True
False
False
False
Explanation: In Python, an object is considered falsy if it is:
NoneFalse- Zero (0, 0.0, 0j)
- Empty sequences or collections (”, [], {}, (), set())
Anything else is truthy.
bool('False')→ True: The string'False'is non-empty, so it’s truthy (even though it contains the word “False”).bool('')→ False: An empty string is falsy.bool(0.0)→ False: Zero (as a float) is falsy.bool([])→ False: An empty list is falsy.
Problem 7: String Format with Positional Arguments
What will the output be?
print("{} {} {}".format("seven", "eight", "nine"))Solution
Output:
seven eight nine
Explanation: The {} placeholders are filled sequentially with the positional arguments in order. The first {} gets “seven”, the second gets “eight”, and the third gets “nine”.
Problem 8: String Format with Repeated Indices
What will the output be?
print("{0} is the first, {1} is the second, and {0} is the first again".format("one", "two"))Solution
Output:
one is the first, two is the second, and one is the first again
Explanation: The indices refer to the positional arguments. {0} refers to the first argument (“one”), {1} refers to the second argument (“two”). Since indices can be repeated, {0} appears twice and both refer to “one”.
Problem 9: String Format Mixed Arguments
What will the output be?
print("{0}, {val1}, and {1}.".format("the penguin borrowed a ladder", "the kangaroo came by for a smoke", val1="the otter mugged me"))Solution
Output:
the penguin borrowed a ladder, the otter mugged me, and the kangaroo came by for a smoke.
Explanation: The format string uses a mix of positional and named arguments:
{0}refers to the first positional argument: “the penguin borrowed a ladder”{val1}refers to the named keyword argument: “the otter mugged me”{1}refers to the second positional argument: “the kangaroo came by for a smoke”
Problem 10: String Format Named Arguments
What will the output be?
print("{1} {0} {val1}".format("the penguin borrowed a ladder", "the kangaroo came by for a smoke", val1="the otter mugged me"))Solution
Output:
the kangaroo came by for a smoke the penguin borrowed a ladder the otter mugged me
Explanation: The format string uses positional and named arguments:
{1}refers to the second positional argument: “the kangaroo came by for a smoke”{0}refers to the first positional argument: “the penguin borrowed a ladder”{val1}refers to the named keyword argument: “the otter mugged me”
The order in the format string determines the order in the output, not the order of arguments in the .format() call.