This notebook explains how to manipulate numbers in Python. It also gives examples of the while loop, if statements, and function definitions.
Python supports both integer and floating point numbers. (A floating point number is a decimal approximation to a number.)
3
-2
3.14159
You can distinguish them with the type command. (But mostly, you should not need to.)
type(3)
type(3.14159)
Addition, Subtraction and multiplication behave more or less as you would expect. Note that floating point arithmetic is not exact because numbers are stored in binary and with limited precision.
3+5
3.2-2.6
1.1*2.2
Division always returns a floating point number.
6/2
For integer division, you can use //
. The quotient a//b
returns the greatest integer less than or equal to the fraction \(\frac{a}{b}\).
6//2
7//2
-1//2
The remainder of the division is given by a%b
. Assuming \(b>0\), this always returns an integer \(r\) with \(0 \leq r \leq b-1\) and satisfying r=a-b*(a//b)
.
12%3
13%3
-13%3
You can compute powers with **
.
2**3
1.1**100.1
You can use paretheses to control the order in which an expression is evaluated. The order of operations is the same as for mathematics. (Details on the order are in the Python Language reference.)
The following computes an approximation to the mathematical number \(e\).
(1+1/1000)**1000
You can store a value into a variable with the =
operator. The following computes the area of the 3-4-5 right triangle:
width=3
height=4
width*height/2
Note that the value of a variable can change over time. This is quite useful in programming.
x=0
x=x+1
print("The value of x is now",x)
The print()
command used above is quite useful. It can be used to print a list of strings (quoted text) and variable values. For example:
print("The area of a triangle with width",width,"and height", height,"is",width*height/2,".")
The print()
function is described in §: 3.3 of The Python Standard Library.
Python also has objects True
and False
which are useful for logic.
True
False
You can use ==
to test for equality and !=
to test for inequality.
2+3==5
2-5==3
2+3!=5
You can also test for less than <
, less than or equal to <=
, greater than >
and greater than or equal to >=
.
2<3
5<=2
x=2.2
x**2 > 9
This is a list of the basic numerical operations built into Python:
x+y
|
addition |
x-y
|
subtraction |
-x
|
negation |
x*y
|
multiplication |
x/y
|
division: returns \(\frac{x}{y}\). |
x//y
|
floored division: returns \(\lfloor \frac{x}{y} \rfloor\), where \(\lfloor \cdot \rfloor\) denotes the floor function, i.e., the greatest integer less than or equal to \(\cdot\). |
x%y
|
remainder of division. Assuming \(y\) is a positive number, it returns a number \(z\) satisfying \(0\leq z \leq y\) and \(\frac{x}{y}=\lfloor \frac{x}{y} \rfloor+\frac{z}{y}\). |
x**y
|
exponentiation: returns \(x^y\). |
pow(x,y)
|
exponentiation: returns \(x^y\) same as x**y
|
abs(x)
|
absolute value |
The following table lists the available comparisons:
x==y
|
test for equality: returns true if the numbers are equal and false if not. |
x!=y
|
not equal: returns true if the numbers are unequal and false if they are equal. |
x<y
|
returns true if \(x\) is less than \(y\). |
x>y
|
returns true if \(x\) is greater than \(y\). |
x<=y
|
returns true if \(x\) is less than or equal to \(y\). |
x>=y
|
returns true if \(x\) is greater than or equal to \(y\). |
while
statement¶A while
loop executes as long as the following statement is true. The following prints the numbers 1...10.
i=1
while i<=10:
print(i)
i=i+1
Note that a colon :
was required at the end of the while statement. The two statements underneath were indented with four spaces. Only the indented statements are repeated, as the following example computing 10! illustrates.
i = 1
factorial = 1
while i<=10:
factorial = factorial*i
i = i+1
print(factorial)
if
statement¶An if
statement executes an indented block of code if a statement is true.
a = 5
b = 12
c = 13
if a**2 + b**2 == c**2:
print("This is a Pythagorean triple.")
You can also add an else
block to do something if the statement is false.
n=13
if n%2==0:
print("The number n =",n,"is even.")
else:
print("The number n =",n,"is odd.")
The term elif
is short for "else if". The block under elif
is executed if the statement in the above if
clause is false and the statement after elif
is true.
mets = 5
yankees = 3
if mets > yankees:
print("The Mets win.")
elif mets < yankees:
print("The Yankees win.")
else:
print("The game was a tie.")
You can have multiple elif statements and the else statement at the end is optional. At most one statement will execute (and necessarily one if there is an else clause).
x=3.3
if x<1:
print ("The number x is less than one.")
elif x<2:
print("The number x is in the interval [1,2)")
elif x<3:
print("The number x is in the interval [2,3)")
elif x<4:
print("The number x is in the interval [3,4)")
In Python, a function is a block of code which evaluates depending on some input variables. The code may do something and often returns a value.
Some simple functions emulate mathematical functions. For example, the function \(f(x)=x^2+1\) can be written and evaluated as follows:
def f(x):
return x**2+1
print("f(2) is ",f(2),".")
print("f(-3) is ",f(-3),".")
The function is evaluated until it reaches the end of the block or a return
statement as above. A return
statement tells the function what it evaluates to.
You can have multiple return statements. The following illustrates the function \[g(x)=\begin{cases} x^2 & \text{if $x \geq 0$} \\ -x^2 & \text{otherwise}.\end{cases}\]
def g(x):
if x>=0:
return x**2
else:
return -x**2
print("g(2) is ",g(2),".")
print("g(-2) is ",g(-2),".")
The following computes n factorial.
def factorial(n):
i = 1
factorial = 1
while i<=n:
factorial = factorial*i
i = i+1
return factorial
print("5! is", factorial(5) )
You can pass multiple parameters to a function.
Functions can also return a truth value:
def is_even(n):
return n%2 == 0
print("The statement `5 is even' is", is_even(5) )
The math
module contains more mathematical functions and constants. To use these methods you should import math
first. This makes functions from math callable.
import math
print("The number pi is", math.pi)
print("The sine of 60 degrees is",math.sin(math.pi/3))
The floor
and ceil
functions convert from floats to integers.
print( "The floor of pi is", math.floor(math.pi) )
print( "The ceiling of pi is", math.ceil(math.pi) )
More functions are available. See the description of the math module in the Python Standard Library reference.
Functions can be passed to functions which allows them to solve more general problems. The following function secant_slope
will take as input a real valued function \(f:{\mathbb R} \to {\mathbb R}\) and two input values \(x_1\) and \(x_2\) and produce the slope of the associated secant line (the line joining \(\big(x_1, f(x_1)\big)\) to \(\big(x_1, f(x_1)\big)\)).
def secant_slope(f, x1, x2):
return ( f(x1)-f(x2) )/(x1- x2)
Here are two examples. First we compute the secant line of \(f(x)=x^2\) through the points on the graph with \(x_1=0\) and \(x_2=1\).
def square(x):
return x**2
print("The slope of the secant line is", secant_slope(square, 0, 1))
Now we will compute the secant line of \(f(x)=\cos(x)\) through the points on the graph with \(x_1=0\) and \(x_2=\frac{\pi}{4}\). Note that we don't need to write our own cosine function; we use the math library loaded above.
print("The slope of the secant line is", secant_slope(math.cos, 0, math.pi/4))
The following function computes the area of a triangle from its three side lengths. This is the semiperimeter formula for area of a triangle.
import math
def area(a,b,c):
s=(a+b+c)/2
return math.sqrt(s*(s-a)*(s-b)*(s-c))
print("The area of the the 3-4-5 right triangle is", area(3,4,5))
print("The area of the equilateral triangle with side length one is", area(1,1,1))
The Collatz conjecture asserts that the following function terminates for any integer \(n \geq 1\). This conjecture is still unresolved.
def collatz(n):
while n!=1:
if n%2==0: # if n is even
n = n//2 # divide n by 2
else:
n = 3*n+1 # otherwise when n is odd: multiply by three and add one.
print(n)
We'll test this on the value 101.
collatz(101)
An approximation to a definite integral of a real valued function is \[\int_a^b f(x)~dx \approx \frac{b-a}{n} \sum_{i=0}^{n-1} f\Big(a+\frac{i(b-a)}{n}\Big)\] for large values of \(n\). Here is a function which evaluates this sum on an arbitrary function.
def approximate_integral(f, a, b, n):
step_size = (b-a)/n
i=0
sum=0
while (i<n):
sum = sum + f(a+i*(b-a)/n)
i=i+1
return sum * (b-a) / n
To test this, we approximate the integral \(\int_0^1 x^2~dx\):
def square(x):
return x**2
print("The integral of x^2 over the interval [0,1] is approximately", approximate_integral(square, 0, 1, 100))
We also approximate \(\int_0^\pi \sin(x)~dx\):
print("The integral of sin(x) over the interval [0,pi] is approximately", approximate_integral(math.sin, 0, math.pi, 100))
evalf(x,y)
which takes two numbers \(x\) and \(y\) and returns the value of the expression \(f(x,y)=\frac{3xy+1}{x^2+1}\).
quadratic_maximum(b,c)
which takes two numbers b
and c
and returns the maximal value of the function \(f(x) = c + bx − x^2\).
print_divisors(p)
which takes as input an integer \(p \geq 1\) and prints all its positive divisors.
is_prime(p)
which takes as input an integer \(p \geq 2\) and returns True
if \(p\) is prime and False
if \(p\) is not prime.is_square(n)
which takes as input a integer \(n\) and returns truth-value of the statement "There is an integer \(k\) so that \(n=k^2\)."
sum_of_cubes(n)
which takes as input a positive integer \(n\) and returns the sum \[1^3+2^3+3^3+\ldots+n^3=\sum_{j=1}^n j^3.\]
newtons_method(f,df,x0,n)
which takes as input a function \(f:{\mathbb R} \to {\mathbb R}\), its derivative \(df=f'\) (also a function from \({\mathbb R}\) to \({\mathbb R}\)), an initial point \(x_0\) and an integer \(n \geq 1\). The function should return the value \(x_n\) obtained by iterating Newton's method \(n\) times.
math
module is described in The Python Standard Library, § 9.2. math.