Scope & arguments · Escopo e argumentos
Local variables
- A variable made inside a function is local.
- It only exists while the function runs.
- Code outside the function cannot see it.
Variáveis locais
- Uma variável criada dentro de uma função é local.
- Ela existe apenas enquanto a função é executada.
- Código fora da função não pode vê-la.
def make_message():
note = "secret"
print(note)
make_message()
# print(note) would be an error: note is local
Global variables
- A variable made outside all functions is global.
- A function can read a global value.
- To change a global inside a function you need the
globalkeyword — but it is usually cleaner toreturna value instead.
Variáveis globais
- Uma variável criada fora de todas as funções é global.
- Uma função pode ler um valor global.
- Para alterar um global dentro de uma função, você precisa da palavra-chave
global— mas geralmente é mais limporeturnum valor em vez disso.
Default values
- A parameter can have a default value:
def f(x, step=1):. - If the caller leaves it out, the default is used.
- Parameters with defaults come after the normal ones.
Valores padrão
- Um parâmetro pode ter um valor padrão:
def f(x, step=1):. - Se o chamado omiti-lo, o padrão será usado.
- Parâmetros com padrões vêm depois dos normais.
def power(base, exp=2):
return base ** exp
print(power(5))
print(power(2, 3))
How arguments are passed
- Python passes a reference to the object you give it.
- Numbers and strings are immutable: a function cannot change the caller's value.
- Lists are mutable: changes made inside a function do affect the caller's list.
Como argumentos são passados
- Python passa uma referência ao objeto que você fornece.
- Números e strings são imutáveis: uma função não pode alterar o valor do chamado.
- Listas são mutáveis: alterações feitas dentro de uma função afetam a lista do chamado.
def try_change(n):
n = n + 100 # changes only the local copy
print(n)
x = 5
try_change(x)
print(x) # x is still 5
In Cambridge pseudocode (A-Level 9618)
BYVALpasses a copy (caller unchanged);BYREFshares the same data (caller changed).- ⚠️ These two keywords are A-Level 9618 only. IGCSE 0478 passes every parameter by value; to send a result back you use a
FUNCTIONandRETURNit.
Em pseudocódigo Cambridge (A-Level 9618)
BYVALpassa uma cópia (chamado inalterado);BYREFcompartilha os mesmos dados (chamado alterado).- ⚠️ Essas duas palavras-chave são apenas A-Level 9618. IGCSE 0478 passa todo parâmetro por valor; para enviar um resultado de volta, use um
FUNCTIONeRETURNele.
PROCEDURE Increase(BYREF N : INTEGER)
N ← N + 1
ENDPROCEDURE
PROCEDURE Show(BYVAL N : INTEGER)
OUTPUT N
ENDPROCEDURE
Common mistakes
- A variable made inside a function is local — it cannot be seen outside.
- Arguments fill the parameters in the order you write them.
- To use a result outside,
returnit and store what comes back.
Erros comuns
- Uma variável criada dentro de uma função é local — não pode ser vista fora.
- Argumentos preenchem os parâmetros na ordem em que você os escreve.
- Para usar um resultado fora,
return-o e armazene o que vier de volta.
Now you try
- The checks call your function with different arguments.
- Press Check answer to test your code.
Agora você tenta
- As verificações chamam sua função com diferentes argumentos.
- Clique em Check answer para testar seu código.
Arguments live in the call · Argumentos vivem na chamada
Each call gets its own copy of the arguments — they vanish when it returns. · Cada chamada recebe sua própria cópia dos argumentos — eles desaparecem ao retornar.
Write greet(name, greeting="Hi") that returns · decrescentes greeting, then , , then name, then !. So greet("Sam") is Hi, Sam! and · e greet("Sam", "Hello") is Hello, Sam!. · Escreva greet(name, greeting="Hi") que retorne greeting, depois , , depois name, depois !. Então greet("Sam") é Hi, Sam! e greet("Sam", "Hello") é Hello, Sam!.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write add_item(lst, x) that appends x to the list lst. Do not · não return anything — the caller's list should change because lists are mutable. · Escreva add_item(lst, x) que adicione x à lista lst. Não retorne nada — a lista do chamador deve mudar porque listas são mutáveis.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write between(low, high, x) that returns · decrescentes True if · se x is from low to · até high (inclusive), otherwise False. · Escreva between(low, high, x) que retorne True se x estiver entre low e high (inclusive), caso contrário False.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write make_countdown(start, stop=1) that returns · decrescentes a list counting down from start to · até stop. So make_countdown(3) is [3, 2, 1] and · e make_countdown(5, 3) is [5, 4, 3]. · Escreva make_countdown(start, stop=1) que retorne uma lista contando de volta de start até stop. Então make_countdown(3) é [3, 2, 1] e make_countdown(5, 3) é [5, 4, 3].
Click Run to see the output here. · Clique em Executar para ver a saída aqui.