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

Update 7 files

- /CodeExamples/FunctionCall.ipynb
- /CodeExamples/FunctionFromCommand.ipynb
- /CodeExamples/FunctionPlot.ipynb
- /CodeExamples/FunctionScope.ipynb
- /CodeExamples/GaussianNoisePlot.ipynb
- /CodeExamples/GuessGame.ipynb
- /CodeExamples/ImageShow.ipynb
parent 49337db2
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:46844364 tags: %% Cell type:markdown id:46844364 tags:
# Cos Plot # Cos Plot
%% Cell type:code id:a64ddd0e tags: %% Cell type:code id:a64ddd0e tags:
``` python ``` python
""" """
Example of calling functions within if satements. Example of calling functions within if statements.
Work through this carefully and understand why the funcions get called when they do. Work through this carefully and understand why the funcions get called when they do.
""" """
def FnOne() : # Define a fucntion than return False def FnOne() : # Define a fucntion than return False
print("Function One Called ") print("Function One Called ")
return False return False
def FnTwo(): # Define a function that returns True def FnTwo(): # Define a function that returns True
print("Function Two Called") print("Function Two Called")
return True return True
def main(): # Use the functions with an "and"
print("Result of call with `and' ")
# Use the functions with an "and" if FnOne() and FnTwo():
print("Result of call with `and' ") print("Success")
if FnOne() and FnTwo(): else:
print("Success") print("Failure")
else:
print("Failure") # Use the functions with an "or"
print("\n\nResult of call with `or'")
if FnOne() or FnTwo():
# Use the functions with an "or" print("Success")
print("\n\nResult of call with `or'") else:
if FnOne() or FnTwo(): print("Failure")
print("Success")
else:
print("Failure")
# execute the program
main()
``` ```
......
%% Cell type:markdown id:6838b2de tags: %% Cell type:markdown id:6838b2de tags:
# Hello # Hello
%% Cell type:code id:4200d243 tags: %% Cell type:code id:4200d243 tags:
``` python ``` python
""" """
Example program to show that you read in a function name from the Example program to show that you read in a function name from the
command line and then ececute it command line and then execute it
Try with fnOne, fnTwo, it it also works for math.cos, math.sin, math.log etc Try with fnOne, fnTwo, it it also works for math.cos, math.sin, math.log etc
""" """
import math import math
def fnOne(y): def fnOne(y):
""" """
Create a function Create a function
""" """
print("Funcion one called with y = " + str(y)) print("Function one called with y = " + str(y))
return y # Just return the given vaue return y # Just return the given vaue
def fnTwo(y): def fnTwo(y):
""" """
Create a second function Create a second function
""" """
print("Funcion two called with y = " + str(y)) print("Function two called with y = " + str(y))
return 2*y # Just return double the value return 2*y # Just return double the value
while True: # Keep in a loop
fn = eval(input("function : ")) # Read in function name NOTE: eval()
y = float(input("y value : ")) # Get a parameter value
def main(): z = fn(y) # Call function read in
print("Value returned is : " + str(z))
while True: # Keep in a loop
fn = eval(input("function : ")) # Read in functioon name NOTE: eval()
y = float(input("y value : ")) # Get a parameter value
z = fn(y) # Call function read in
print("Value returned is : " + str(z))
if __name__ == "__main__":
main()
``` ```
......
%% Cell type:markdown id:b452308e tags: %% Cell type:markdown id:b452308e tags:
# Function Plot # Function Plot
%% Cell type:code id:50f5e2c8 tags: %% Cell type:code id:50f5e2c8 tags:
``` python ``` python
""" """
Form a plot of a function using a function plotting function Form a plot of a function using a function plotting function
""" """
import math import math
import matplotlib.pyplot as plt # Import the plot package as plt import matplotlib.pyplot as plt # Import the plot package as plt
def examplefunction(x): def examplefunction(x):
""" """
Define a function of a single variable Define a function of a single variable
""" """
return math.log(x) + math.atan(x) return math.log(x) + math.atan(x)
def function_plot(min,max,npts,fn): def function_plot(min,max,npts,fn):
""" """
Function to form the x/y from a function Function to form the x/y from a function
""" """
delta = (max - min)/npts delta = (max - min)/npts
x = min x = min
x_data = [] x_data = []
y_data = [] y_data = []
# # Fill the x/y arrays using the supplied function.
# Fill the x/y arrays using the supplied function.
while x <= max: while x <= max:
x_data.append(x) x_data.append(x)
y = fn(x) y = fn(x)
y_data.append(y) y_data.append(y)
x += delta x += delta
# Return the x and y lists # Return the x and y lists
return x_data,y_data return x_data, y_data
def main(): # Get the x and y lists from the plot function
x_data, y_data = function_plot(1.0,4.0,100,examplefunction)
# Get the x and y lists from the plot function # Plot them
x_data , y_data = function_plot(1.0,4.0,100,examplefunction) plt.plot(x_data,y_data,"g") # Default plot in green
plt.title("Plot of quadratic") # Add title/lables
# Plot them plt.xlabel("x value")
plt.plot(x_data,y_data,"g") # Default plot in green plt.ylabel("y value")
plt.title("Plot of quadratic") # Add title/lables plt.show() # show the actual plot
plt.xlabel("x value")
plt.ylabel("y value")
plt.show() # show the actual plot
main()
``` ```
......
%% Cell type:markdown id:6838b2de tags: %% Cell type:markdown id:6838b2de tags:
# Hello # Hello
%% Cell type:code id:4200d243 tags: %% Cell type:code id:4200d243 tags:
``` python ``` python
""" """
Here is an example of how NOT to use globals. Here is an example of how NOT to use globals.
Look as this an try an find out what went wrong Look as this and try and find out what went wrong
""" """
vals = [] vals = []
def add_values(vals): def add_values(vals):
x = 0.0 # Local variable x = 0.0 # Local variable
for y in vals: # Sum up values in list for y in vals: # Sum up values in list
x += y x += y
return x # return local value return x # return local value
def main(): def main():
localVals = vals # want to make a localVals localVals = vals # want to make a localVals
for i in range(0,10): for i in range(0,10):
x = 5.0*i x = 5.0*i
localVals.append(x) # Append to localVals localVals.append(x) # Append to localVals
vals.append(x) # Append to vals vals.append(x) # Append to vals
x = add_values(localVals) # Sum up with function x = add_values(localVals) # Sum up with function
print("Sum of values is : " + str(x)) # Print print("Sum of values is : " + str(x)) # Print
# Contents of vals is # Contents of vals is
print("Local vals is : \n" + str(localVals)) print("Local vals is : \n" + str(localVals))
print("Global vals is : \n" + str(vals)) print("Global vals is : \n" + str(vals))
# Try and disentangle what is happending here; its syntactically correct Python # Try and disentangle what is happending here; its syntactically correct Python
# but it illustartes how dargerous globas can be...... this is real bug found in # but it illustartes how dargerous globas can be...... this is real bug found in
# a piece of student code (after a lot of searching) # a piece of student code (after a lot of searching)
main() main()
``` ```
......
%% Cell type:markdown id:0758d75a tags: %% Cell type:markdown id:0758d75a tags:
# Gaussian Noise Plot # Gaussian Noise Plot
%% Cell type:code id:f0193150 tags: %% Cell type:code id:f0193150 tags:
``` python ``` python
""" """
Plot a histogram of Gaussian noise Plot a histogram of Gaussian noise
""" """
import math import math
import random import random
import matplotlib.pyplot as plt # Import the plot package as plt import matplotlib.pyplot as plt # Import the plot package as plt
def main(): point = 10000 # Number of points
gauss_data = [] # list to hold points
mean = 20.0 # mean of noise
sd = 2.0 # standard deviation of noise
point = 10000 # Number of points
gauss_data = [] # list to hold points
mean = 20.0 # mean of noise
sd = 2.0 # standard deviation of noise
while point >= 0: # Fill list with gauss randoms
while point >= 0: # Fill list with gauss randoms gauss_data.append(random.gauss(mean,sd))
gauss_data.append(random.gauss(mean,sd)) point -= 1
point -= 1
# Plot histogram with 40 bins and range of mean +/- 3sd
# Plot histogram with 40 bins and range of mean +/- 3sd plt.hist(gauss_data, bins = 40, range = [mean - 3*sd , mean + 3*sd])
plt.hist(gauss_data, bins = 40, range = [mean - 3*sd , mean + 3*sd]) plt.title("Histogram of Gaussian Noise")
plt.title("Histogram of Gaussian Noise") plt.show()
plt.show()
main()
``` ```
......
%% Cell type:markdown id:a21a577a tags: %% Cell type:markdown id:a21a577a tags:
# Hello # Hello
%% Cell type:code id:cf5ba095 tags: %% Cell type:code id:cf5ba095 tags:
``` python ``` python
""" """
Simple guess game that will loop until you get it right. Simple guess game that will loop until you get it right.
Be very careful that you follow the indentation here. Be very careful that you follow the indentation here.
""" """
import random import random
def main(): correct = random.randint(1,9) # the randon correct value
correct = random.randint(1,9) # the randon correct value print("Guess the number between 1 and 9")
print("Guess the number between 1 and 9")
number_of_tries = 0 number_of_tries = 0
while True: # Start of infinite loop while True: # Start of infinite loop
guess = int(input("Have a guess (give an int) : ")) guess = int(input("Have a guess (give an int) : "))
number_of_tries += 1 number_of_tries += 1
if guess == correct: # Test if the guess is correct if guess == correct: # Test if the guess is correct
print("You guessed right") print("You guessed right")
break # If correct break the loop break # If correct break the loop
else: else:
print("You guessed wrong.... have another go") print("You guessed wrong.... have another go")
# End of loop # End of loop
# This is after loop. # This is after loop.
print("You took " + str(number_of_tries) + " attempt to guess right") print("You took " + str(number_of_tries) + " attempt to guess right")
main()
``` ```
......
%% Cell type:markdown id:6838b2de tags: %% Cell type:markdown id:6838b2de tags:
# Hello # Hello
%% Cell type:code id:4200d243 tags: %% Cell type:code id:4200d243 tags:
``` python ``` python
""" """
Example to read a image file using the matplotlib image module Example to read a image file using the matplotlib image module
and display it. It will work with all common image formats and display it. It will work with all common image formats
Try with the supplied "stones.jpg" file. (stones on a Scottish beach) Try with the supplied "stones.jpg" file. (stones on a Scottish beach)
""" """
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib.image as img # Import image module import matplotlib.image as img # Import image module
def main(): filename = str(input("Graphics file : "))
filename = str(input("Graphics file : "))
image = img.imread(filename) # Read the jpeg image = img.imread(filename) # Read the jpeg
plt.imshow(image) # render it in plot axis plt.imshow(image) # render it in plot axis
plt.show() # display it plt.show() # display it
main()
``` ```
......
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