Functions · Funções
Name a block of code
- A function is named code you can use again and again.
- Make one with
def name():and an indented body. - "Calling" the function by its name runs that code.
Nomear um bloco de código
- Uma função é código nomeado que você pode usar repetidamente.
- Crie uma com
def name():e um corpo recuado. - "Chamar" a função pelo seu nome executa esse código.
Give it inputs (parameters)
- The names in the brackets are parameters — the function's inputs.
- When you call it, you pass in arguments (the real values).
- A function can take more than one parameter.
Fornecer entradas (parâmetros)
- Os nomes entre colchetes são parâmetros — as entradas da função.
- Ao chamá-la, você passa argumentos (os valores reais).
- Uma função pode ter mais de um parâmetro.
def shout(word):
print(word.upper() + "!")
shout("hello")
Send back a result (return)
returnsends a value back to whoever called the function.- You can store that value or use it in an expression.
returnalso ends the function straight away.
Enviar um resultado de volta (return)
returnenvia um valor de volta para quem chamou a função.- Você pode armazenar esse valor ou usá-lo em uma expressão.
returntambém encerra a função imediatamente.
def double(x):
return x * 2
result = double(5)
print(result)
return vs print
printonly shows something on the screen.returngives a value back that the rest of your code can use.- A function with no
returngives backNone.
return vs print
printapenas exibe algo na tela.returndevolve um valor que o restante do seu código pode usar.- Uma função sem
returndevolveNone.
In Cambridge pseudocode
- A
FUNCTIONreturns a value; aPROCEDUREjust does an action.
Em pseudocódigo do Cambridge
- Um
FUNCTIONretorna um valor; umPROCEDUREapenas executa uma ação.
FUNCTION Add(A : INTEGER, B : INTEGER) RETURNS INTEGER
RETURN A + B
ENDFUNCTION
PROCEDURE Greet(Name : STRING)
OUTPUT "Hello, ", Name
ENDPROCEDURE
Common mistakes
- A function returns
Noneunless you writereturn; printing is not the same as returning. - Run a function with
():greet(), notgreet. - Define a function before you call it.
Erros comuns
- Uma função retorna
Nonea menos que você escrevareturn; imprimir não é o mesmo que retornar. - Execute uma função com
():greet(), nãogreet. - Defina uma função antes de chamá-la.
Now you try
- Define each function, then the checks will call it for you.
- Use
returnto send the answer back (do notprintit).
Agora você tenta
- Defina cada função, então as verificações a chamarão para você.
- Use
returnpara enviar a resposta de volta (nãoprintela).
Calling a function · Chamando uma função
A call pushes a frame with its arguments; return pops it. · Uma chamada empilha um frame com seus argumentos; return desempilha ele.
Write a function add(a, b) that returns · decrescentes the sum of a and · e b. · Escreva uma função add(a, b) que retorne a soma de a e b.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a function greet(name) that returns · decrescentes the string Hello, then the name then !. So greet("Sam") returns · decrescentes Hello, Sam!. · Escreva uma função greet(name) que retorna a string Hello, seguida do nome e depois !. Então greet("Sam") retorna Hello, Sam!.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a function biggest(a, b) that returns · decrescentes the larger of the two values. If they are equal, return either one. · Escreva uma função biggest(a, b) que retorne o maior dos dois valores. Se forem iguais, retorne qualquer um.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write is_palindrome(word) that returns · decrescentes True when the word reads the same backwards (like racecar), otherwise False. · Escreva is_palindrome(word) que retorne True quando a palavra for lida igual para trás (como racecar), caso contrário False.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.