MATH0011: Mathematical Methods II
Code we wrote during lecture 1
python
# This is our first exampleprint("Hello World")
# These are examples of arithmetic
print(23+10)
print(23-10)
print(23*10)
print(23/10)
# to the power of
print(2**10)
# integer division
print(23//10)
# modulo (the remainder when divided by)
print(23%10)
# complex numbers
print((5+2j)**2)
# using the math module
import math
print(math.sin(1))
print(math.cos(2))
print(math.log(5))
print(math.e)
print(math.pi)
print(math.tau)
# uncomment the following line to print help
#help(math)
# defining and using variables
a = 3
b = 5
number = 10
long_name_for_my_variable = 5
# The following two lines are the same
a = a+1
a += 1
print(a)
print(a**number)
# example 1
a = 5
a += 2
print(a)
# example 2
a = 5
a *= 2
a += 4
print(a)
# example 3
a = 3
b = 2
a += b
b *= a
print(b)
print(a)
# True and False
a = True
b = False
print(not a)
print(a or b)
print(a and b)
print((a and not b) or b or not a)
# Testing for equality, etc
a = 3
print(a == 3)
print(a != 4)
print(7 > 4)
print(7 > 10 or 4 < 10)
# if conditionals
a = 4
if a%2 == 0:
print(a)
# example 1
a = 7
if a%2 == 0:
print("a is even")
elif a%3 == 0:
print("a is odd and a is a multiple of 3")
else:
print("a is odd and not a multiple of 3")
# for loops
for i in range(1,3):
print(i)
print("Done")
# example 1: evan square numbers
for i in range(1,21):
if i%2 == 0:
print(i**2)
# example 2: prime numbers
for i in range(1,21):
a = True
for j in range(2,i):
if i%j == 0:
a = False
if a:
print(i)
# while loops
i = 1
while i < 10:
print(i)
i *= 2
# example 1: even square numbers
i = 1
while i < 21:
if i%2 == 0:
print(i**2)
i += 1
# example 2: lowest triangle number that is larger than 100
tot = 0
i = 1
while tot < 100:
tot += i
i += 1
print(tot)
print(i)
# break
for i in range(1,1000):
if i%3 == 0 and i%5 == 0:
print(i)
break
# continue
for i in range(20):
if i%3 == 0:
continue
print(i)
# pass
for i in range(100):
if i%3 == 0:
pass
else:
print(i)
# Printing Fibonacci numbers up to 1000
# first solution
f1 = 1
f2 = 1
while f1 <= 1000:
print(f1)
new_f1 = f2
new_f2 = f1+f2
f1 = new_f1
f2 = new_f2
# second (and slightly tidier) solution
f1 = 1
f2 = 1
while f1 <= 1000:
print(f1)
new_f1 = f2
f2 = f1+f2
f1 = new_f1
# third (that I finished after the lecture) solution
f1 = 1
f2 = 1
while f1 <= 1000:
print(f1)
f2 = f1+f2
f1 = f2-f1