mscroggs.co.uk
mscroggs.co.uk

subscribe

MATH0011: Mathematical Methods II

Code we wrote during lecture 1

 python 
# This is our first example
print("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
= 3
= 5
number = 10
long_name_for_my_variable = 5

# The following two lines are the same
= a+1
+= 1

print(a)
print(a**number)

# example 1
= 5
+= 2
print(a)

# example 2
= 5
*= 2
+= 4
print(a)

# example 3
= 3
= 2
+= b
*= a
print(b)
print(a)

# True and False
= True
= 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
= 3

print(a == 3)
print(a != 4)
print(7 > 4)
print(7 > 10 or 4 < 10)

# if conditionals
= 4
if a%2 == 0:
    print(a)

# example 1
= 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
= 1
while i < 10:
    print(i)
    i *= 2

# example 1: even square numbers
= 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
= 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

© Matthew Scroggs 2012–2024