Python - 문제 미리보기
문제 1851
medium
함수 내부에서 전역 변수를 생성하거나 수정할 때 사용하는 키워드는?
```python
def myfunc():
_______ x
x = "fantastic"
myfunc()
print("Python is " + x)
```
정답: B
⦁ `global` 키워드의 역할:
```python
def myfunc():
global x # x를 전역 변수로 선언
x = "fantastic" # 전역 스코프에 x 생성
myfunc()
print("Python is " + x) # "Python is fantastic"
```
⦁ `global` 키워드 사용 시나리오:
1. 함수 내부에서 전역 변수 생성:
```python
def create_global():
global new_var
new_var = "I'm global now!"
create_global()
print(new_var) # "I'm global now!"
```
2. 함수 내부에서 전역 변수 수정:
```python
counter = 0 # 전역 변수
def increment():
global counter # 전역 counter 수정하겠다는 선언
counter += 1 # 전역 counter 값 증가
increment()
print(counter) # 1
increment()
print(counter) # 2
```
💡 학습 팁
이 문제를 포함한 Python 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.