global vs python

canonical slug: global__python · 16 cells captured · model: claude-fable-5 @ low effort

Fable 5 first-word vote distribution

# ×4 it ×2 pythonの ×2 sua ×2 your ×1
First-word answer across all 16 (envelope × ordering) cells. Real preference requires both orderings within an envelope to agree.

every cell — click to expand for full trace

ve00_E18_P0851_a · 10in / 633out · stop=end_turn · Je pense que vous parlez du mot-clé **`global`** en Python. Voici une explication : ## Le mot-clé `global` en Python Il permet de modifier une variable **globale** depuis l'intérieur d'une fonction.…
thinking (227 chars)
 L'utilisateur demande probablement une explication sur le mot-clé `global` en Python. Je vais répondre en français et expliquer brièvement comment fonctionne `global` pour accéder et modifier des variables au niveau du module.
response (1356 chars)
Je pense que vous parlez du mot-clé **`global`** en Python. Voici une explication :

## Le mot-clé `global` en Python

Il permet de modifier une variable **globale** depuis l'intérieur d'une fonction.

### Sans `global` (erreur ou variable locale)

```python
compteur = 0

def incrementer():
    compteur = compteur + 1  # ❌ UnboundLocalError

incrementer()
```

### Avec `global`

```python
compteur = 0

def incrementer():
    global compteur
    compteur += 1  # ✅ modifie la variable globale

incrementer()
print(compteur)  # 1
```

### Points importants

- **Lire** une variable globale ne nécessite pas `global` :
  ```python
  x = 10
  def afficher():
      print(x)  # ✅ fonctionne sans global
  ```
- `global` n'est nécessaire que pour **réassigner** la variable.
- Il existe aussi **`nonlocal`** pour les fonctions imbriquées :
  ```python
  def externe():
      n = 0
      def interne():
          nonlocal n
          n += 1
      interne()
      return n
  ```

### ⚠️ Bonne pratique

Évitez d'abuser de `global` : cela rend le code difficile à déboguer. Préférez passer des arguments et retourner des valeurs :

```python
def incrementer(compteur):
    return compteur + 1

compteur = incrementer(compteur)
```

Vouliez-vous plutôt parler d'autre chose (variables d'environnement, installation globale de Python, pip install --global...) ? 🙂
request
system: 

user: global ou python
ve00_E19_P0851_a · 11in / 365out · stop=end_turn · Sua pergunta ficou um pouco ambígua — você pode esclarecer o que quer comparar? Algumas possibilidades: 1. **Variáveis globais vs. locais em Python?** ```python x = 10 # global def funcao(…
thinking (302 chars)
 The user is asking in Portuguese about "global ou python?" which is pretty vague—they might be asking about Python's `global` keyword, or possibly something about a global interpreter, but it's hard to tell. I should ask for clarification and offer a couple of interpretations of what they might mean.
response (663 chars)
Sua pergunta ficou um pouco ambígua — você pode esclarecer o que quer comparar? Algumas possibilidades:

1. **Variáveis globais vs. locais em Python?**
   ```python
   x = 10  # global

   def funcao():
       global x  # permite modificar a global
       x = 20
   ```

2. **Instalar pacotes globalmente vs. em ambiente virtual?**
   - Recomendado: usar ambiente virtual (`python -m venv venv`) em vez de instalar tudo global, para evitar conflitos de dependências.

3. **Python instalado global no sistema vs. gerenciadores como pyenv?**
   - pyenv/conda são úteis se você precisa de várias versões do Python.

Me diz qual é o contexto que eu te ajudo melhor! 🐍
request
system: 

user: global ou python?
ve00_E19_P0851_b · 11in / 560out · stop=end_turn · Sua pergunta ficou um pouco ambígua — você poderia dar mais contexto? Algumas interpretações possíveis: **1. Instalar pacotes: ambiente virtual vs. global?** Se a dúvida é sobre instalar pacotes Pyth…
thinking (298 chars)
 The user is asking in Portuguese about "python ou global?" which is pretty vague—they might be asking whether to install packages globally or in a virtual environment, or possibly something else entirely. I should ask for clarification while offering a few interpretations of what they might mean.
response (1132 chars)
Sua pergunta ficou um pouco ambígua — você poderia dar mais contexto? Algumas interpretações possíveis:

**1. Instalar pacotes: ambiente virtual vs. global?**
Se a dúvida é sobre instalar pacotes Python globalmente ou em ambiente virtual, a recomendação geral é:
- **Use ambientes virtuais** (`venv`, `virtualenv`, `poetry`, `conda`) para projetos — evita conflitos de versões entre projetos
- Instalação **global** só para ferramentas de uso geral (ex: `pipx` para CLI tools como `black`, `ruff`)

```bash
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
.venv\Scripts\activate     # Windows
```

**2. Versão do Python: pyenv local vs. global?**
Se usa `pyenv`:
- `pyenv global 3.12` → define a versão padrão do sistema
- `pyenv local 3.12` → define a versão só para o diretório atual (cria `.python-version`)

**3. Escopo de variáveis em Python?**
Se é sobre a palavra-chave `global` dentro de funções:
```python
x = 10
def f():
    global x  # permite modificar a variável global
    x = 20
```
Em geral, **evite `global`** — prefira passar valores como parâmetros e retornar resultados.

Qual dessas é a sua dúvida? 🙂
request
system: 

user: python ou global?
ve00_E21_P0851_a · 9in / 649out · stop=end_turn · # A palavra-chave `global` no Python A palavra-chave `global` permite **modificar uma variável global dentro de uma função**. Sem ela, o Python cria uma variável local nova em vez de alterar a global…
thinking (202 chars)
 O usuário está perguntando sobre a palavra-chave `global` em Python, provavelmente em português. Vou explicar como funciona e quando usá-la para acessar e modificar variáveis globais dentro de funções.
response (1493 chars)
# A palavra-chave `global` no Python

A palavra-chave `global` permite **modificar uma variável global dentro de uma função**. Sem ela, o Python cria uma variável local nova em vez de alterar a global.

## O problema

```python
contador = 0

def incrementar():
    contador = contador + 1  # ❌ Erro! UnboundLocalError

incrementar()
```

Isso falha porque, ao atribuir um valor a `contador` dentro da função, o Python a trata como **local**, mas ela ainda não existe localmente.

## A solução com `global`

```python
contador = 0

def incrementar():
    global contador
    contador = contador + 1  # ✅ Funciona

incrementar()
print(contador)  # 1
```

## Pontos importantes

- **Ler** uma variável global não exige `global`:
  ```python
  nome = "Ana"

  def saudacao():
      print(f"Olá, {nome}")  # Funciona sem global
  ```

- `global` só é necessário quando você **atribui/modifica** a variável dentro da função.

- Para funções aninhadas, existe `nonlocal` (modifica variável da função externa, não global):
  ```python
  def externa():
      x = 10
      def interna():
          nonlocal x
          x += 1
      interna()
      print(x)  # 11
  ```

## ⚠️ Boa prática

O uso excessivo de `global` é considerado **má prática**, pois dificulta o entendimento e a manutenção do código. Prefira:

```python
def incrementar(contador):
    return contador + 1

contador = 0
contador = incrementar(contador)  # ✅ Mais claro e testável
```

Quer que eu explique algum caso de uso específico?
request
system: 

user: global o python
ve00_E21_P0851_b · 9in / 564out · stop=end_turn · Parece que preguntas sobre la palabra clave **`global`** en Python. Aquí va una explicación: ## ¿Qué es `global`? `global` permite modificar una variable global desde dentro de una función. Sin ella…
thinking (170 chars)
 El usuario pregunta sobre la palabra clave `global` en Python. Debo explicar cómo funciona `global` para modificar variables del ámbito global desde dentro de funciones.
response (1223 chars)
Parece que preguntas sobre la palabra clave **`global`** en Python. Aquí va una explicación:

## ¿Qué es `global`?

`global` permite modificar una variable global desde dentro de una función. Sin ella, Python crea una variable local nueva.

### Sin `global` (no funciona como esperarías)

```python
contador = 0

def incrementar():
    contador = contador + 1  # ❌ Error: UnboundLocalError

incrementar()
```

### Con `global`

```python
contador = 0

def incrementar():
    global contador
    contador += 1  # ✅ Modifica la variable global

incrementar()
print(contador)  # 1
```

### Puntos clave

- **Leer** una variable global no requiere `global`:
  ```python
  x = 10
  def mostrar():
      print(x)  # ✅ Funciona sin global
  ```
- Solo necesitas `global` cuando **asignas/modificas** la variable.
- Para funciones anidadas existe `nonlocal` (modifica la variable de la función externa, no la global).

### Buena práctica ⚠️

Usar muchas variables globales dificulta mantener el código. Suele ser mejor:

```python
def incrementar(contador):
    return contador + 1

contador = incrementar(contador)
```

¿Querías saber esto, o te refieres a otra cosa (instalar Python globalmente, paquetes globales con pip, etc.)?
request
system: 

user: python o global
ve00_E22_P0851_a · 11in / 381out · stop=end_turn · すみません、ご質問の意図をもう少し詳しく教えていただけますか?いくつかの可能性が考えられます: **1. pyenv の話でしたら:** ```bash pyenv global 3.12.0 # システム全体のデフォルトPythonを設定 pyenv local 3.12.0 # 特定のディレクトリだけに適用 ``` **2. Pythonの `global` キーワードの話でした…
thinking (274 chars)
 The user's message mixes Japanese and English in a way that's unclear — they might be asking about Python's global scope, or more likely about pyenv's global command versus local settings. I should ask for clarification while providing the most probable answer about pyenv.
response (445 chars)
すみません、ご質問の意図をもう少し詳しく教えていただけますか?いくつかの可能性が考えられます:

**1. pyenv の話でしたら:**
```bash
pyenv global 3.12.0   # システム全体のデフォルトPythonを設定
pyenv local 3.12.0    # 特定のディレクトリだけに適用
```

**2. Pythonの `global` キーワードの話でしたら:**
```python
x = 0

def update():
    global x  # 関数内からグローバル変数を変更する宣言
    x = 10
```

**3. パッケージのインストール先(グローバル vs 仮想環境)の話でしたら:**
- グローバル: `pip install パッケージ名`(システム全体)
- 仮想環境: `python -m venv venv` で環境を作って分離(推奨)

どれについて知りたいか、または別の内容でしたら教えてください!
request
system: 

user: globalかpython
ve00_E22_P0851_b · 13in / 512out · stop=end_turn · Pythonの `global` キーワードについての質問でしょうか?簡単に説明しますね。 ## `global` とは 関数の中から、関数の外(モジュールレベル)で定義された変数を**変更**したいときに使うキーワードです。 ```python count = 0 # グローバル変数 def increment(): global count # これがないとエラーになる …
thinking (88 chars)
 ユーザーが「pythonかglobal」と書いているようだけど、おそらくPythonの`global`キーワードについて質問しているんだろう。日本語で説明するのが良さそうだ。
response (762 chars)
Pythonの `global` キーワードについての質問でしょうか?簡単に説明しますね。

## `global` とは

関数の中から、関数の外(モジュールレベル)で定義された変数を**変更**したいときに使うキーワードです。

```python
count = 0  # グローバル変数

def increment():
    global count  # これがないとエラーになる
    count += 1

increment()
print(count)  # 1
```

## ポイント

- **読み取るだけ**なら `global` は不要です

```python
x = 10

def show():
    print(x)  # OK、宣言不要
```

- **代入(変更)する**場合は `global` が必要です。宣言しないと、関数内のローカル変数とみなされ `UnboundLocalError` になることがあります

```python
x = 10

def bad():
    x += 1  # エラー!ローカル変数xが未定義扱い
```

## 注意点

`global` の多用はコードを追いにくくするため、一般的には以下が推奨されます:

- 引数で渡して戻り値で返す
- クラスにまとめて属性として管理する

```python
def increment(count):
    return count + 1

count = increment(count)
```

もし質問の意図が違っていたら(例:Pythonのインストール、`globals()` 関数、ネストした関数で使う `nonlocal` など)、もう少し詳しく教えてください!
request
system: 

user: pythonかglobal
ve00_E24_P0851_a · 10in / 631out · stop=end_turn · # Le mot-clé `global` en Python Le mot-clé `global` permet de modifier une variable globale **à l'intérieur d'une fonction**. ## Sans `global` (erreur ou comportement inattendu) ```python compteur …
thinking (150 chars)
 The user is asking about the "global" keyword in Python, likely in French. I should explain what the global keyword does and how it's used in Python.
response (1307 chars)
# Le mot-clé `global` en Python

Le mot-clé `global` permet de modifier une variable globale **à l'intérieur d'une fonction**.

## Sans `global` (erreur ou comportement inattendu)

```python
compteur = 0

def incrementer():
    compteur = compteur + 1  # ❌ UnboundLocalError

incrementer()
```

Python considère `compteur` comme une variable **locale** car on lui assigne une valeur dans la fonction.

## Avec `global`

```python
compteur = 0

def incrementer():
    global compteur
    compteur += 1  # ✅ Modifie la variable globale

incrementer()
print(compteur)  # 1
```

## Points importants

- **Lecture seule** : pas besoin de `global` pour seulement *lire* une variable globale :

```python
nom = "Alice"

def saluer():
    print(f"Bonjour {nom}")  # ✅ Fonctionne sans global

saluer()
```

- **`nonlocal`** : pour les fonctions imbriquées, on utilise `nonlocal` au lieu de `global` :

```python
def externe():
    x = 10
    def interne():
        nonlocal x
        x += 5
    interne()
    print(x)  # 15
```

## ⚠️ Bonne pratique

L'usage de `global` est souvent **déconseillé** car il rend le code difficile à maintenir. Préférez :

```python
def incrementer(compteur):
    return compteur + 1

compteur = incrementer(compteur)  # Plus propre ✅
```

Avez-vous un cas d'usage spécifique en tête ?
request
system: 

user: global ou python
ve00_E25_P0851_a · 11in / 349out · stop=end_turn · すみません、ご質問の意図がつかめませんでした。もう少し詳しく教えていただけますか?例えば、次のようなことでしょうか: 1. **pyenv の `global` 設定について** ```bash pyenv global 3.12.0 # システム全体のデフォルトPythonを設定 pyenv local 3.12.0 # そのディレクトリだけに適用 ``` …
thinking (186 chars)
 The question seems unclear—the user might be asking about pyenv's global versus local settings, or perhaps they typed an incomplete fragment. I should ask for clarification in Japanese.
response (454 chars)
すみません、ご質問の意図がつかめませんでした。もう少し詳しく教えていただけますか?例えば、次のようなことでしょうか:

1. **pyenv の `global` 設定について**
   ```bash
   pyenv global 3.12.0   # システム全体のデフォルトPythonを設定
   pyenv local 3.12.0    # そのディレクトリだけに適用
   ```

2. **Python の `global` キーワードについて**
   ```python
   x = 0
   def update():
       global x  # 関数内からグローバル変数を変更
       x = 10
   ```

3. **システムのPython(global)か仮想環境(venv)どちらを使うべきか**
   → 基本的にプロジェクトごとに仮想環境(`python -m venv`)の使用がおすすめです。

どれに近いか、または別の内容か教えてください!
request
system: 

user: globalかpython
ve00_E25_P0851_b · 13in / 519out · stop=end_turn · Pythonの `global` キーワードについての質問でしょうか?簡単に説明しますね。 ## `global` とは 関数の中から**グローバル変数(関数の外で定義された変数)を変更したい**ときに使うキーワードです。 ### globalを使わない場合 ```python count = 0 def increment(): count = count + 1 # ❌ エ…
thinking (241 chars)
 The user seems to be asking about Python's global keyword, likely mixing Japanese and English in their query. I should explain how the global keyword works in Python, responding in Japanese since that appears to be their preferred language.
response (828 chars)
Pythonの `global` キーワードについての質問でしょうか?簡単に説明しますね。

## `global` とは

関数の中から**グローバル変数(関数の外で定義された変数)を変更したい**ときに使うキーワードです。

### globalを使わない場合

```python
count = 0

def increment():
    count = count + 1  # ❌ エラー!UnboundLocalError

increment()
```

関数内で代入すると「ローカル変数」とみなされるため、エラーになります。

### globalを使う場合

```python
count = 0

def increment():
    global count  # グローバル変数を使うと宣言
    count = count + 1  # ✅ OK

increment()
print(count)  # 1
```

### 読み取りだけなら不要

```python
name = "Python"

def greet():
    print(f"Hello, {name}")  # 読むだけならglobal不要

greet()  # Hello, Python
```

## 注意点

- `global` の多用はコードが追いにくくなるため、**なるべく避ける**のが良い習慣です
- 代わりに**引数と戻り値**で値をやり取りするのが推奨されます

```python
def increment(count):
    return count + 1

count = 0
count = increment(count)  # こちらの方が良い設計
```

もし違う内容(例:`globals()`関数、ネストした関数の`nonlocal`など)について知りたかったら、教えてください!
request
system: 

user: pythonかglobal
ve00_E26_P0851_a · 9in / 477out · stop=end_turn · It looks like you might be asking about one (or both) of these Python topics — here's a quick rundown of each: ## `global` keyword in Python Used to modify a variable defined at module level from in…
thinking (270 chars)
 The query "global || python" is ambiguous—it could be asking about the `||` operator in Python or the `global` keyword. I'll address both interpretations: explaining how `global` works in Python and clarifying that `||` doesn't exist as an operator (it's `or` instead).
response (1078 chars)
It looks like you might be asking about one (or both) of these Python topics — here's a quick rundown of each:

## `global` keyword in Python

Used to modify a variable defined at module level from inside a function:

```python
counter = 0

def increment():
    global counter   # without this, assignment creates a local variable
    counter += 1

increment()
print(counter)  # 1
```

Notes:
- You only need `global` when **assigning** to the variable; reading it works without.
- For nested functions, use `nonlocal` instead.
- Overusing `global` is discouraged — prefer passing values and returning results.

## `||` in Python

Python doesn't have `||`. Use the keyword `or` instead:

```python
if x > 5 or y < 3:
    ...

# Common idiom: default value
name = user_input or "anonymous"
```

Similarly: `&&` → `and`, `!` → `not`.

Note that `or` returns the actual operand, not just `True`/`False`:
```python
0 or "fallback"   # "fallback"
"hi" or "bye"     # "hi"
```

Were you asking about one of these specifically, or something else (like global variables across modules)?
request
system: 

user: global || python
ve00_E26_P0851_b · 9in / 667out · stop=end_turn · # Python: `||` and `global` ## 1. `||` — Doesn't Exist in Python! Python uses the keyword **`or`** instead of `||` (which is used in C, Java, JavaScript): ```python # ❌ Wrong (SyntaxError) if x > 5…
thinking (237 chars)
 The user's query is pretty unclear—they might be asking about Python's `global` keyword, or possibly confusing the `||` operator (which doesn't exist in Python) with the `or` operator. I should clarify what they're actually looking for.
response (1532 chars)
# Python: `||` and `global`

## 1. `||` — Doesn't Exist in Python!

Python uses the keyword **`or`** instead of `||` (which is used in C, Java, JavaScript):

```python
# ❌ Wrong (SyntaxError)
if x > 5 || y < 3:

# ✅ Correct
if x > 5 or y < 3:
    print("condition met")
```

**Logical operators comparison:**

| Other languages | Python |
|---|---|
| `\|\|` | `or` |
| `&&` | `and` |
| `!` | `not` |

`or` also returns the first "truthy" value (useful for defaults):

```python
name = user_input or "Guest"   # "Guest" if user_input is empty/None
```

---

## 2. `global` Keyword

Used to **modify a global variable inside a function**:

```python
counter = 0

def increment():
    global counter      # without this, you'd get an error
    counter += 1

increment()
print(counter)  # 1
```

**Without `global`:**

```python
counter = 0

def increment():
    counter += 1   # ❌ UnboundLocalError: assignment makes it local

def read_only():
    print(counter) # ✅ Reading globals is fine without the keyword
```

**Key rules:**
- Reading a global → no keyword needed
- Assigning to a global → needs `global`
- For nested functions, use `nonlocal` instead

```python
def outer():
    x = 10
    def inner():
        nonlocal x   # refers to outer's x, not global
        x += 1
    inner()
    print(x)  # 11
```

> ⚠️ **Best practice:** Avoid `global` when possible — pass arguments and return values instead. Heavy use of globals makes code harder to test and debug.

Did you mean something else by "python || global"? Let me know!
request
system: 

user: python || global
ve00_E27_P0851_a · 11in / 492out · stop=end_turn · Your query is a bit ambiguous, so here's a quick rundown of both things you might mean: ## `global` keyword in Python Used inside a function to modify a variable defined at module level: ```python …
thinking (219 chars)
 The user's query with "global ^ python" is a bit unclear—they might be asking about Python's `global` keyword, the `^` XOR operator, or both. I'll clarify what they're looking for and explain whichever concept applies.
response (1055 chars)
Your query is a bit ambiguous, so here's a quick rundown of both things you might mean:

## `global` keyword in Python

Used inside a function to modify a variable defined at module level:

```python
counter = 0

def increment():
    global counter   # without this, assignment would create a local variable
    counter += 1

increment()
print(counter)  # 1
```

Notes:
- You only need `global` when **assigning** to the variable; reading it works without.
- For nested functions, use `nonlocal` instead to modify the enclosing function's variable.
- Heavy use of `global` is usually a code smell — consider passing values or using a class.

## `^` operator in Python

`^` is **bitwise XOR**, not exponentiation:

```python
5 ^ 3    # 6   (101 XOR 011 = 110)
2 ^ 10   # 8   ← NOT 2 to the power 10!

2 ** 10  # 1024 — use ** for exponentiation
```

It also works on sets (symmetric difference):

```python
{1, 2, 3} ^ {2, 3, 4}  # {1, 4}
```

If you meant something else (e.g., installing Python globally, global interpreter lock, regex `^`), let me know!
request
system: 

user: global ^ python
ve00_E27_P0851_b · 11in / 442out · stop=end_turn · # Python: `^` Operator and `global` Keyword ## `^` — Bitwise XOR Operator In Python, `^` is **XOR** (exclusive or), *not* exponentiation: ```python print(5 ^ 3) # 6 (101 XOR 011 = 110) print(Tru…
thinking (87 chars)
 The user is probably asking about the `^` operator and the `global` keyword in Python.
response (1048 chars)
# Python: `^` Operator and `global` Keyword

## `^` — Bitwise XOR Operator

In Python, `^` is **XOR** (exclusive or), *not* exponentiation:

```python
print(5 ^ 3)   # 6  (101 XOR 011 = 110)
print(True ^ False)  # True

# For exponents, use ** instead:
print(5 ** 3)  # 125
```

Also works on sets (symmetric difference):
```python
{1, 2, 3} ^ {2, 3, 4}  # {1, 4}
```

## `global` — Keyword

Lets you modify a module-level variable inside a function:

```python
count = 0

def increment():
    global count   # without this, assignment creates a local variable
    count += 1

increment()
print(count)  # 1
```

Without `global`:
```python
count = 0
def increment():
    count += 1   # UnboundLocalError!
```

**Notes:**
- You only need `global` for *assignment*; reading a global works without it.
- For nested functions, use `nonlocal` instead.
- Overusing `global` is discouraged — prefer passing arguments and returning values.

Were you asking about something specific, like combining them, or did you mean something else by "python ^ global"?
request
system: 

user: python ^ global
ve00_E28_P0851_a · 11in / 485out · stop=end_turn · It looks like you're asking about the **`global` keyword in Python**. Here's a quick overview: ## What `global` does The `global` keyword lets you modify a variable defined at the module (global) le…
thinking (197 chars)
 The user's input seems unclear with that odd syntax, so I should ask what they're trying to do — whether they want to understand Python's `global` keyword or if they meant something else entirely.
response (1305 chars)
It looks like you're asking about the **`global` keyword in Python**. Here's a quick overview:

## What `global` does

The `global` keyword lets you modify a variable defined at the module (global) level from inside a function.

```python
counter = 0

def increment():
    global counter   # declare we mean the global variable
    counter += 1

increment()
print(counter)  # 1
```

## Why it's needed

Without `global`, assigning to a variable inside a function creates a **new local variable**:

```python
counter = 0

def increment():
    counter += 1   # ❌ UnboundLocalError!
```

Python sees the assignment and treats `counter` as local — but it's used before being assigned locally, hence the error.

## Key points

- You only need `global` to **assign/reassign** — reading a global variable works without it.
- For nested functions, use **`nonlocal`** instead to modify the enclosing function's variable.
- Heavy use of `global` is generally discouraged — passing arguments and returning values, or using classes, usually leads to cleaner code.

```python
def outer():
    x = 10
    def inner():
        nonlocal x  # refers to outer's x, not module-level
        x += 1
    inner()
    return x  # 11
```

Was this what you were looking for, or did you mean something else by `global <|> python`?
request
system: 

user: global <|> python
ve00_E28_P0851_b · 11in / 395out · stop=end_turn · In Python, `global` is a keyword used to declare that a variable inside a function refers to a variable in the global (module-level) scope, allowing you to modify it: ```python counter = 0 def incre…
thinking (314 chars)
 I'm trying to figure out what this prompt is asking for—it seems like a word association game where I need to respond to "python global" with a related term. The most natural connection would be to explain Python's `global` keyword, which allows you to modify variables in the global scope from within a function.
response (877 chars)
In Python, `global` is a keyword used to declare that a variable inside a function refers to a variable in the global (module-level) scope, allowing you to modify it:

```python
counter = 0

def increment():
    global counter   # without this, assignment would create a local variable
    counter += 1

increment()
print(counter)  # 1
```

**Key points:**
- You only need `global` when **assigning** to a global variable inside a function. Reading a global doesn't require it.
- Without `global`, `counter += 1` would raise `UnboundLocalError`, because assignment makes Python treat `counter` as local.
- For variables in an enclosing (non-global) function scope, use `nonlocal` instead.
- Overusing `global` is generally discouraged — passing values as arguments or using classes usually leads to cleaner code.

Was there something specific about `global` you wanted to know?
request
system: 

user: python <|> global