1. Misleading Variable Scope
This snippet demonstrates the tricky nature of variable scope in Python, particularly with nested functions.
def outer_function():
x = "outer"
def inner_function():
nonlocal x
x = "inner"
print("Inner x:", x)
inner_function()
print("Outer x:", x)
outer_function()
#clcoding.com
Inner x: inner
Outer x: inner
2. Mutable Default Arguments
This snippet shows the common pitfall of using mutable default arguments in function definitions.
def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list
print(append_to_list(1))
print(append_to_list(2))
print(append_to_list(3))
#clcoding.com
[1]
[1, 2]
[1, 2, 3]
3. Unexpected Behavior with Floating Point Arithmetic
Floating-point arithmetic can be non-intuitive due to precision issues.
a = 0.1
b = 0.2
c = 0.3
print(a + b == c)
print(f"{a + b:.17f}")
#clcoding.com
False
0.30000000000000004
4. Changing a List While Iterating
This snippet demonstrates the pitfalls of modifying a list while iterating over it.
numbers = [1, 2, 3, 4, 5]
for i in numbers:
if i % 2 == 0:
numbers.remove(i)
print(numbers)
#clcoding.com
[1, 3, 5]
5. Unpacking and Extended Unpacking
Python allows for complex unpacking operations which can be tricky to understand at first glance.
a, b, *c, d = range(6)
print(a)
print(b)
print(c)
print(d)
# Nested unpacking
x, (y, z) = (1, (2, 3))
print(x)
print(y)
print(z)
#clcoding.com
0
1
[2, 3, 4]
5
1
2
3
0 Comments:
Post a Comment