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

Update 8 files

- /CodeExamples/InsideSphere.ipynb
- /CodeExamples/IntegerFormat.ipynb
- /CodeExamples/LineCount.ipynb
- /CodeExamples/ListAccess.ipynb
- /CodeExamples/ListofFunctions.ipynb
- /CodeExamples/MainScope.ipynb
- /CodeExamples/MakeandAppendList.ipynb
- /CodeExamples/MultiplyByLogs.ipynb
parent 0d3dacfd
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:3afb0d80 tags: %% Cell type:markdown id:3afb0d80 tags:
# Inside Sphere # Inside Sphere
%% Cell type:code id:d7072d10 tags: %% Cell type:code id:d7072d10 tags:
``` python ``` python
""" """
Demonstrate a logical function to test if a point is inside or Demonstrate a logical function to test if a point is inside or
outside of a sphere of give radius. outside of a sphere of given radius.
""" """
import math import math
def inside(radius, x, y, z): def inside(radius, x, y, z):
""" """
Check if point x,y,x is inside a sphere of radius r Check if point x,y,x is inside a sphere of radius r
""" """
lenSqr = x*x + y*y + z*z # length squared; this avoids sqrt() for efficiency. lenSqr = x*x + y*y + z*z # length squared; this avoids sqrt() for efficiency.
if lenSqr <= radius*radius : # Is inside sphere if lenSqr <= radius*radius : # Is inside sphere
return True # Return logical True return True # Return logical True
else: # Else outside else: # Else outside
return False # Return logical False return False # Return logical False
radius = 5.0
def main(): x = float(input("X value : "))
radius = 5.0 y = float(input("Y value : "))
x = float(input("X value : ")) z = float(input("Z value : "))
y = float(input("Y value : "))
z = float(input("Z value : ")) if inside(radius,x,y,z): # Use the function above to do the work
print("Point is inside sphere of radius : " + str(radius))
if inside(radius,x,y,z): # Use the function above to do the work else:
print("Point is inside sphere of radius : " + str(radius)) print("Point is outside sphere of radius : " + str(radius))
else:
print("Point is outside sphere of radius : " + str(radius))
main()
``` ```
......
%% Cell type:markdown id:f4a0d181 tags: %% Cell type:markdown id:f4a0d181 tags:
# Make and Append List # Make and Append List
%% Cell type:code id:0b78a654 tags: %% Cell type:code id:0b78a654 tags:
``` python ``` python
""" """
Make a simple list, and append to it Make a simple list, and append to it
""" """
def main(): myList = [0,1,4,9,16,25,36]
myList = [0,1,4,9,16,25,36] print("The initial list is : " + str(myList))
print("The initial list is : " + str(myList)) l = len(myList)
l = len(myList) print("Length of list is " + str(l))
print("Length of list is " + str(l))
myList.append(49) myList.append(49)
print("The list after appending an element is : " + str(myList)) print("The list after appending an element is : " + str(myList))
main()
``` ```
......
%% 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 program to open a file and count the number of lines in the file. Example program to open a file and count the number of lines in the file.
This example also show how to trap the most common (and annoying) problem of typing This example also shows how to trap the most common (and annoying) problem of typing
the wrong filename. If you are new to coding, ignore this and come back an look at it the wrong filename. If you are new to coding, ignore this and come back and look at it
at the end of the course. at the end of the course.
Try with "burns.txt" Try with "burns.txt"
""" """
# Prompt for file name and open it for reading
# This has a more complex structure to trap errors
while True: # Go into infinite loop
try: # try: test for errors
file = str(input("Filename : ")) # Prompt for name
filein = open(file, "r") # Open file
break # If here, success, so break out of loop
except: # Catch the error, so failed to open file
print("Failed to open file : {0:s}".format(file)) # Print error message then back to loop
# Read in the data to a list of strings.
data = filein.readlines()
filein.close() # Close file, optional, but good pratcice
def main(): print("Number of lines in file is :" + str(len(data)))
# Prompt for file name and open it for reading
# This has a more compplex stucture to trap errors
while True: # Go into infinite loop
try: # try: test for errors
file = str(input("Filename : ")) # Prompt for name
filein = open(file, "r") # Open file
break # If here, success, so break out of loop
except: # Catch the error, so failed to open file
print("Failed to open file : {0:s}".format(file)) # Print error message then back to loop
# Read in the data to a list of strings.
data = filein.readlines()
filein.close() # Close file, optional, but good pratcice
print("Number of lines in file is :" + str(len(data)))
# Run 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
""" """
A more advanced program that shows new ways to access list data A more advanced program that shows new ways to access list data
without using the range() function. without using the range() function.
""" """
import math import math
def main(): # Create a list of numbers from 0->4pi
nPoints = 50
# Create a list of numbers fro 0->4pi thetaData = []
# theta = 0.0
nPoints = 50 maxTheta = 4 * math.pi
thetaData = [] dtheta = maxTheta / nPoints
theta = 0.0
maxTheta = 4*math.pi while theta < maxTheta:
dtheta = maxTheta / nPoints thetaData.append(theta)
theta += dtheta
while theta < maxTheta:
thetaData.append(theta) # Assess the list with the enumerate function that returns the
theta += dtheta # element index and element value as a two element truple
for i,theta in enumerate(thetaData):
# Assess the list with the enumerate function that returns the print("Element : " + str(i) + " has value : " + str(theta))
# element index and element value as a two element truple
for i,theta in enumerate(thetaData):
print("Element : " + str(i) + " has value : " + str(theta)) # Make a second list of cos Data
cosData = []
for theta in thetaData:
# Make a second list of cos Data cos = math.cos(theta)
cosData = [] cosData.append(cos)
for theta in thetaData:
cos = math.cos(theta) # Now access the two list in parallel with the zip function
cosData.append(cos) # to merge them into truples, one from each list.
for theta,cos in zip(thetaData,cosData):
# Now access the two list in parallel with the zip function print("Theta: " + str(theta) + " Cos(theta) " + str(cos))
# to merge them into truples, one from each list.
for theta,cos in zip(thetaData,cosData):
print("Theta: " + str(theta) + " Cos(theta) " + str(cos))
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 create a list of fucntions and then call them from Example program to create a list of functions and then call them from
a loop. a loop.
This program illustrated the flexibility of functions, also that you can have This program illustrates the flexibility of functions, also that you can have
list of anything, in this case you have a list of functions !! lists of anything, in this case you have a list of functions !!
This is a rather dangerous language feature and while it shows the flexibility of lists and This is a rather dangerous language feature and while it shows the flexibility of lists and
functions, it is not an advised progarmming method since the scope for obscure code is functions, it is not an advised programming method since the scope for obscure code is
unlimited. unlimited.
""" """
import math import math
def myFn(y): def myFn(y):
# Create own local function that returns a value # Create own local function that returns a value
return 1 - math.erf(y) return 1 - math.erf(y)
def main(): # Make a list of, both from math library and lovcal
functions = [math.cos,math.sin,math.tan,myFn]
# Make a list of, both from math library and lovcal
functions = [math.cos,math.sin,math.tan,myFn]
x = float(input("X value : ")) # Read in float from command line
x = float(input("X value : ")) # Read in float from command line for fn in functions: # Access the list of functions
y = fn(x) # Use each elemenst of the list as a function.
for fn in functions: # Access the list of functions print("Value from " + str(fn) + " is : " + str(y))
y = fn(x) # Use each elemenst of the list as a function. # Note str(fn) gives the correct information but in a rather messy way.
print("Value from " + str(fn) + " is : " + str(y))
# Note str(fn) gives the correct information but in rather messeg way.
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 show scope of variable in a main() program. Example to show scope of variable in a main() program.
""" """
ag = 34.56 # Define in three global values. ag = 34.56 # Define in three global values.
bg = 41.45 bg = 41.45
x = 100.0 x = 100.0
def main(): def main():
""" """
The main programme The main programme
""" """
global ag # Make ag writable within main() global ag # Make ag writable within main()
# Print out values, not bg can be read. # Print out values, note bg can be read.
print("Value of ag in main is : " + str(ag) + " and bg is : " + str(bg)) print("Value of ag in main is : " + str(ag) + " and bg is : " + str(bg))
ag += 10 # Undate value of ag inside main() ag += 10 # Undate value of ag inside main()
print("New Value is ag is : " + str(ag)) print("New Value is ag is : " + str(ag))
x = 30.0 # Declare x inside main (note NEW variable) and NOT global. x = 30.0 # Declare x inside main (note NEW variable) and NOT global.
print("Internal value of x is : " + str(x)) print("Internal value of x is : " + str(x))
# Run main rogram # Run main rogram
main() main()
# Do an external print to check globals.
# Do an external print to check globals.
print("External value of ag is : " + str(ag)) print("External value of ag is : " + str(ag))
print("External value of x is : " + str(x)) print("External value of x is : " + str(x))
``` ```
......
%% Cell type:markdown id:2bb00e31 tags: %% Cell type:markdown id:2bb00e31 tags:
# Make and Append List # Make and Append List
%% Cell type:code id:08a543df tags: %% Cell type:code id:08a543df tags:
``` python ``` python
""" """
Make a simple list, and append to it Make a simple list, and append to it
""" """
def main(): myList = [0,1,4,9,16,25,36]
myList = [0,1,4,9,16,25,36] print("The initial list is : " + str(myList))
print("The initial list is : " + str(myList)) l = len(myList)
l = len(myList) print("Length of list is " + str(l))
print("Length of list is " + str(l))
myList.append(49) myList.append(49)
print("The list after appending an element is : " + str(myList)) print("The list after appending an element is : " + str(myList))
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
""" """
Python program to demonstrate multiple and divide by logs. Python program to demonstrate multiplication and division by logs.
Try for various vales, what happens if the numbers are negative ? Try for various vales, what happens if the numbers are negative ?
""" """
import math # get the maths functions import math # get the maths functions
def main(): # Read in two floats
a = float(input("Value a : "))
# Read in two floats b = float(input("Value b : "))
a = float(input("Value a : "))
b = float(input("Value b : ")) # Calculate the natural log of each
al = math.log(a)
# Calcualte the natural log of each bl = math.log(b)
al = math.log(a)
bl = math.log(b) # Do a multiply by logs
c = math.exp(al + bl)
# Do a multiply by logs # Print out the result
c = math.exp(al + bl) print("Multiply by logs : " + str(c) + " and by normal multiply : " + str(a*b))
# Print out the result
print("Multiply by logs : " + str(c) + " and by normal multiply : " + str(a*b)) # Do a divide by logs
c = math.exp(al - bl)
# Do a divide by logs # Print out tghe result.
c = math.exp(al - bl) print("Divide by logs : " + str(c) + " and by normal divide : " + str(a/b))
# Print out tghe result.
print("Divide by logs : " + str(c) + " and by normal divide : " + str(a/b))
# run the main()
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