Quick actions

cmd+k|ctrl+k

Navigation

Languages

Walrus, Scope, Global, Nonlocal

Snippet info

Language

Python

Visibility

public

Author

akaimal04

Created

2024-12-29T00:08:11.720406Z

Updated

2024-12-29T00:08:11.720406Z

# Walrus Operator

txt = "helloooooooo"

if (n := len(txt)) > 10:
    print(f"too long - {n} elements")
    
    
while (n := len(txt)) > 1:
    print(n)
    txt = txt[:-1]
    
print(txt)



# Scope - what variables do I have access to?
def function():
    total = 0
    
# print(total) - won't work bc of function scope

# Scope rules
    #1 - start w local
    #2 - parent local?
    #3 - global 
    #4 - built in python functions
    
    
print("\n")
    
#Global
total = 0

def counter():
    global total
    total += 1
    return total
    
counter();
counter();
print(counter());


  
print("\n")
    
# Non Local
def outer():
    x = "local"
    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner: ", x)
        
    inner()
    print("outer: ", x)
    
outer()


INFO