Friday, 24 May 2024

5 Tricky Python code snippets


 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

Popular Posts

Categories

AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (893) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses