@@ -106,9 +106,7 @@ For example:
106
106
- [ char()] ( #char )
107
107
- [ float()] ( #float )
108
108
- [ int()] ( #int )
109
- - [ Scope] ( #scope )
110
- - [ Local Variables] ( #local-variables )
111
- - [ Global Variables] ( #global-variables )
109
+ - [ Local / Global Variables] ( #local--global-variables )
112
110
113
111
## Digital I/O
114
112
@@ -1388,9 +1386,38 @@ int_value = int(value)
1388
1386
print (" Int value:" , int_value)
1389
1387
```
1390
1388
1391
- ## Scope
1389
+ ## Local / Global Variables
1392
1390
1393
- ### Local Variables
1391
+ Variables can either be globally or locally declared:
1394
1392
1395
- ### Global Variables
1393
+ - Global variables can be accessed anywhere in the program.
1394
+ - Local variables can only be accessed within the function it is declared.
1396
1395
1396
+ When creating a program, you can decide whether you want certain variables accessible from anywhere, or just within the function.
1397
+
1398
+ The benefit of declaring a local variable is that it uses less memory space (as it is only assigned within the function).
1399
+
1400
+ The con of declaring a local variable is that it is not accessible anywhere else in the program.
1401
+
1402
+ ``` python
1403
+ global_var = 0 # initial value
1404
+
1405
+ def my_function ():
1406
+ local_var = 10 # declare local variable
1407
+ print ()
1408
+ print (" (inside function) local_var is: " , local_var)
1409
+
1410
+ global_var = local_var + 25
1411
+ print (" (inside function) global_var is updated to: " , global_var)
1412
+
1413
+ return global_var
1414
+
1415
+ global_var = my_function() + 25
1416
+ print (" (outside function) global_var is finally: " , global_var)
1417
+
1418
+ '''
1419
+ The line below will cause the script to fail
1420
+ because it is not declared globally.
1421
+ '''
1422
+ # print(local_var)
1423
+ ```
0 commit comments