Skip to content
Snippets Groups Projects
Commit 10f7f3bb authored by cprutean's avatar cprutean
Browse files

Update 2 files

- /CourseNotes/basicfunctions.ipynb
- /CourseNotes/Scope.ipynb
parent cbe2be6f
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Scope of Variables
*Scope of variables* means the parts of code where a particular variable
is accessible. When you were writing a single program this was simple,
but as you start to use functions and `main()` you need to start to think.
## All Local Variables
> ### Key Point
If you define **all** your variables inside functions then the rule is
simple
- Variables are local to the function in which they are defined.
So if we take the example below which forms a list of numbers and then
uses function `add_values()` to sum them up.
```python
def add_values(values):
x = 0.0 # Local variable
for y in values: #Sum up values in list
x += y
return x # return local value
def main():
v = [] # make list of numbers
for i in range(0,10):
x = 5.0*i
v.append(x)
x = add_values(v) # Sum up with function
print("Sum of values is : " + str(x)) # Print
main()
```
- The `x` used in `add_values()` is local to that function, it is used to hold the sum of the elements of the list and its **value** is returned in line 5
- The `x` used (twice) in `main()` is a *completely separate* to the same named variable in `add_values()`, and in particular it is located in a different location in computer memory, so the value of one does *not* affect the other.
> ### Key Point
Use of local variables is the recommended programming style, it
- Makes each function separate and removes inter-dependancies
- Allows each function to operate independently of others, so easier
to reuse in other applications.
- Easier to test and debug each function seperately.
> **Note: functions have *no memory* from any previous call, so all local variables get re-created every time the function is called.**
## Global Variables
When variables are declared outside functions, including outside `main()` they become *global*, so
```python
wave = 6.5 # Declare outside main or fucntion
def bright(x):
val = x*wave # Can access global variable wave
return val
def main():
v = bright(15.0)
print("value of bright is : " + str(v) + " and can also access wave " + str(wave))
```
- In Line 1, `wave` is a global float variable declared outside any function.
- In Line 4 and 9 the value of `wave` is accessible. It is also accesible from *any* other function declared within this file.
>> Here is a longer example of using a global variable
In this case `wavelength` is visible within both `main()` and the function `planck()`.
> ### Key Point: Rules
The rules for global variables are:
- The global variable must be decared before any function it is used
>The rules for global variables are:
>- The global variable must be decared before any function it is used
in, so typically at the top of the file.
- It is visible from all functions declared within the file.
- The value of a global **cannot** be changed from within any function
>- It is visible from all functions declared within the file.
>- The value of a global **cannot** be changed from within any function
or `main()`, so it is “*Read Only*”.
> Global variables look *like a good thing*, but they should be used with *extreme care* and only when you want to set a *global default* across a set of functions.
## Changing Globals
The default operation of globals is that they are *read only* within
each function, but you can override this by the use of the `global` keyword as shown below.
```python
wave = 6.5 # Declare outside main or funtion
def bright(x):
val = x*wave # Can access global variable wave
return val
def main():
global wave # make wave writable fron within main
v = bright(15.0)
print("value of bright is : " + str(v) + " and can also access wave " + str(wave))
wave = 25.0 # Update global variable
v = bright(15.0)
print("value of bright is : " + str(v) + " and can also access wave with new value " + str(wave))
```
So here in line 8 we have declared that `wave` is a writable global in `main()`, so when we update it in line 12 the value seen by function `bright()` also changes.
> ### Wrong
Using `global` to make global variables writable within functions is *very dangerous*; it leads to totally unmaintanable code and should only be used when you really understand what you are doing.
> WARNING: Having lists in global is a recipe for disaster, there are all sorts of horrible and none obvious consequences; how it works is logical, but typically not what you want; just “don’t do it”.
%% Cell type:code id: tags:
``` python
```
......
%% Cell type:markdown id: tags:
%% Cell type:markdown id:e1a67568 tags:
# Basic Functions
## Main as a function
Now that you have seen the use of ```functions``` to calculate mathematical expressions
such as ```cos()```, we will see how we can use the same idea to break up your code
into smaller and manageable sections.
The first concept in breaking up your code is to write your program as a ```function```, called ```main()``` as shown below:
```python
def main():
print("Hello world")
main()
```
Here we have
- **Line 1** declares the start of a ```function``` called ```main()```. *Note: the ":" is a
required part of the syntax*
- **Line 2** contains the body of the function, here to simply ```print()``` "Hello
World", *Note: this must be indented by exactly 4 spaces*.
- **Line 4** executes the ```main()``` function, so running the program.
### Key Point
As you can see, correct indentation in `Python` is *essential* - it
is part of the syntax of the language.
The editor will allow you to use key to do the indentation but you
absolutely *must* get the right every time. There is no margin for
error!
> #### More on indentation
In computing languages there are *three* styles to
designate the start and end of code blocks, these being
1. *brackets*, in `C` and `Java` style languages,
2. *keywords* in `Fortran` and `Shell` scripts.
3. *indentation* in `Python`.
> So in most languages *indentation* of code blocks is *good style* but
not essential. However (uniquely?) in `Python` the start and end of blocks are
designated by *indentation* only; it is part of the syntax of `Python`. This
makes `Python` code short and concise, but it does mean you *must* get the
indentation absolutely right!
Failing to do this is the biggest source of (some very interesting)
bugs!
> Modify your program for Checkpoint1 to use a `main()` function.
## Simple functions
The power of ```functions``` becomes apparent once we look at functions that can take
*parameters*. Lets consider the code below that uses two functions to
convert temperature values between the centigrade and fahrenheit scale:
```python
def fahrenheit(t):
return 1.8*t + 32.0
def centigrade(t):
return (t - 32.0)/1.8
def main():
ct = 100.0
ft = fahrenheit(ct)
print("Temperature of " + str(ct) + " in centigrade is " + str(ft) + " in farenheit")
ft = 200.0
ct = centigrade(ft)
print("Temperature of " + str(ft) + " in farenheit is " + str(ct) + " in centigrade")
main()
```
Looking at this in detail,
- **Line 1** declares a function called `fahrenheit()` that takes a value `t` as a
parameter assumed to be in centigrade.
- **Line 2** is the body of the function that takes the value of `t` and calculates the fahrenheit value and `return`s it.
- **Line 4-5** defines a function called `centigrade()` that takes a value `t` as a parameter assumed to be in fahrenheit and returns the value in centigrade.
- **Line 9** uses the `fahrenheit()` function.
- **Line 12** uses the `centigrade()` function.
> Have a look at these two programs and play with them:
>- [Temperature Converter](../CodeExamples/TemperatureConverter.ipynb)
>- [Quadratic](../CodeExamples/QuadraticFunction.ipynb)
### Key Point
This looks like an unnecessary complication, but as your programs get more complex you will see the benefit.
**You are expected to use this format in all your programs**. In particular
- Declare `functions` at the top of the code.
- The executed program called `main()` which is defined and then executed by `main()` at the **end** of the file.
- **ALL** variables must be declared within `functions()` or `main()`
This is *good programming practice* that we want you to learn, it also avoids many of the problems, pitfalls and complications associated with *scope of variables*, details of which are in the optional sections at
the end of the course.
- [Scope of variables](Scope.ipynb)
You will see how to do more complex operations with functions later, but this will get you started for now.
%% Cell type:code id: tags:
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment