Scope & arguments
Local variables
- A variable made inside a function is local.
- It only exists while the function runs.
- Code outside the function cannot see it.
지역 변수
- 함수 내부에서 생성된 변수는 지역 변수입니다.
- 이 변수는 함수가 실행되는 동안에만 존재합니다.
- 함수 외부의 코드는 이 변수를 볼 수 없습니다.
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.
전역 변수
- 모든 함수 외부에서 생성된 변수는 전역 변수입니다.
- 함수는 전역 변수의 값을 읽을 수 있습니다.
- 함수 내에서 전역 변수를 변경하려면
global키워드를 사용해야 하지만, 일반적으로 더 깔끔하게return하는 것이 좋습니다.
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.
기본값
- 매개변수는 기본값을 가질 수 있습니다:
def f(x, step=1):. - 호출자가 생략하면 기본값이 사용됩니다.
- 기본값이 있는 매개변수는 정상적인 매개변수 다음에 와야 합니다.
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.
인자가 전달되는 방식
- Python은传入하는 객체에 대한 참조를 전달합니다.
- 숫자와 문자열은 불변성: 함수가 호출자의 값을 변경할 수 없습니다.
- 목록은 가변성: 함수 내부에서 이루어진 변경사항은 호출자의 목록에도 영향을 미칩니다.
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.
Cambridges 가짜 코드(A-Level 9618)
BYVAL는 복사본을 전달합니다(호출자 변화 없음);BYREF는 동일한 데이터를 공유합니다(호출자 변화 있음).- ⚠️ 이 두 키워드는 A-Level 9618 전용입니다. IGCSE 0478는 모든 매개변수를 값으로 전달하며, 결과를 다시 보내려면
FUNCTION를 사용하고 이를RETURN해야 합니다.
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.
흔한 실수
- 함수 내에서 생성된 변수는 로컬이며, 외부에서는 볼 수 없습니다.
- 인수는 작성한 순서대로 매개변수에 채워집니다.
- 결과를 외부에서 사용할 때,
return하고 반환된 값을 저장하세요.
Now you try
- The checks call your function with different arguments.
- Press Check answer to test your code.
이제 직접 해보기
- 검증 과정은 다른 인자를 사용하여 함수를 호출합니다.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
Arguments live in the call
Each call gets its own copy of the arguments — they vanish when it returns.
Write greet(name, greeting="Hi") that returns greeting, then , , then name, then !. So greet("Sam") is Hi, Sam! and greet("Sam", "Hello") is Hello, Sam!.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write add_item(lst, x) that appends x to the list lst. Do not return anything — the caller's list should change because lists are mutable.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write between(low, high, x) that returns True if x is from low to high (inclusive), otherwise False.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write make_countdown(start, stop=1) that returns a list counting down from start to stop. So make_countdown(3) is [3, 2, 1] and make_countdown(5, 3) is [5, 4, 3].
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.