In [4]:
import numpy as np
import scipy.constants as constants
print('Pi = ', constants.pi)
In [5]:
h = float(input("Enter the height of the tower (in metres): "))
t = float(input("Enter the time interval (in seconds): "))
s = constants.g*t**2/2
print("The height of the ball is",h-s,"meters")
Link to What's in Scipy.constants: https://docs.scipy.org/doc/scipy/reference/constants.html
(and numpy)
In [3]:
x = 4**0.5
print(x)
x = np.sqrt(4)
print(x)
Here we'll practice writing our own functions.
Functions start with
def name(input):
and must end with a statement to return the value calculated
return x
To run a function your code would look like this:
import numpy as np
def name(input)
FUNCTION CODE HERE
return D
y=int(input("Enter y:"))
D = name(y)
print(D)
First - write a function to calculate n factorial. Reminder:
$n! = \pi^n_{k=1} k$
~
~
~
~
~
~
~
~
~
~
~
~
~
~
In [1]:
def factorial(n):
f = 1.0
for k in range(1,n+1):
f *= k
return f
print("This programme calculates n!")
n = int(input("Enter n:"))
a = factorial(10)
print("n! = ", a)
Finding distance to the origin in cylindrical co-ordinates:
In [2]:
from math import sqrt, cos, sin
def distance(r,theta,z):
x = r*cos(theta)
y = r*sin(theta)
d = sqrt(x**2+y**2+z**2)
return d
D = distance(2.0,0.1,1.5)
print(D)
In [6]:
def factors(n):
factorlist=[]
k = 2
while k<=n:
while n%k==0:
factorlist.append(n)
n //= k
k += 1
return factorlist
list=factors(12)
print(list)
In [7]:
print(factors(17556))
In [8]:
print(factors(23))
The reason these are useful are for things like the below, where you want to make the same calculation many times. This finds all the prime numbers (only divided by 1 and themselves) from 2 to 100.
In [9]:
for n in range(2,100):
if len(factors(n))==1:
print(n)
In [ ]: