Dino Geek, try to help you

How to use global and local variables in Python?


In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

Here is an example of a global variable:

```
x = “global”

def foo(): print(“x inside :”, x)

foo()
print(“x outside:”, x)
```

Output would be:
```
x inside : global
x outside: global
```

If you want to use same name for different scope, you can create a local variable with the same name. A variable declared inside the function’s body or in the local scope is known as a local variable.

```
x = “global”

def foo(): x = x * 2 print(x)
foo()
```
This will output an error because Python treats x as a local variable and x is not defined in local scope.

If you want to modify global variable from a function, global keyword is used before the variable name.

```
x = “global “

def foo(): global x x = x * 2 print(x)
foo()
```

Output:
```
global global
```

Python has `nonlocal` statement for nested functions that allows to assign to variables in the nearest enclosing scope that is not global. `nonlocal` keyword works similar to `global`, but it works with the nearest enclosing scope.

```
def outer(): x = “local”

def inner(): nonlocal x x = “nonlocal“ print(“inner:”, x) inner() print(“outer:”, x)

outer()
```

Output:
```
inner: nonlocal
outer: nonlocal
```


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use