Escopo

Como escrever funções em Python

Shayne Miel

Software Architect @ Duo Security

Nomes

tom

Como escrever funções em Python

Nomes

tom e janelle

Como escrever funções em Python

Escopo

tom e janelle

Como escrever funções em Python

Escopo

tom, janelle e outro tom

Como escrever funções em Python

Escopo

x = 7
y = 200
print(x)
7
def foo():
    x = 42
    print(x)
    print(y)
foo()
42
200
print(x)
7
Como escrever funções em Python

Escopo

pergunta sobre escopo

Como escrever funções em Python

Escopo

escopo local

Como escrever funções em Python

Escopo

escopo global

Como escrever funções em Python

Escopo

escopo embutido

Como escrever funções em Python

Escopo

escopo não local

Como escrever funções em Python

A palavra-chave global

x = 7

def foo():
  x = 42
  print(x)

foo()
42
print(x)
7
x = 7

def foo():
  global x
  x = 42
  print(x)

foo()
42
print(x)
42
Como escrever funções em Python

A palavra-chave nonlocal

def foo():
  x = 10

  def bar():
    x = 200
    print(x)

  bar()
  print(x)

foo()
200
10
def foo():
  x = 10

  def bar():
    nonlocal x
    x = 200
    print(x)

  bar()
  print(x)

foo()
200
200
Como escrever funções em Python

Vamos praticar!

Como escrever funções em Python

Preparing Video For Download...