MTH 337: Week 1

Printing

  • print is a function.
  • "Hello World!" is the argument to print.

"Hello World!" is a string - a sequence of characters surrounded by enclosing quotation marks.

In [1]:
print("Hello World!")
Hello World!

Mathematical operations

In [2]:
2 + 2 # Addition
Out[2]:
4
In [3]:
10 - 3 # Subtraction
Out[3]:
7
In [4]:
6 * 7 # Multiplication
Out[4]:
42
In [5]:
5/2 # Division
Out[5]:
2.5
In [6]:
1 # 1 is recognized by Python as an integer
Out[6]:
1
In [7]:
1. # 1. is recognized by Python as a float (floating point number)
Out[7]:
1.0
In [8]:
1 + 1 # The sum of two integers is an integer
Out[8]:
2
In [9]:
1 + 1. # The sum of an integer and a float is a float
Out[9]:
2.0
In [10]:
2**5 # The ** operator is used for powers
Out[10]:
32
In [11]:
26 % 5 # The % operator is used to find the modulus (remainder after division)
Out[11]:
1
In [12]:
abs(-88) # Absolute value
Out[12]:
88

Variable assignment using the = operator

In [13]:
g = 9.81 # Assigning the value 9.81 to the variable g
In [14]:
g # g takes on the value 9.81, which is substituted in whenever g is used
Out[14]:
9.81
In [15]:
g*2
Out[15]:
19.62
In [16]:
x = 1
y = 2
z = x + y # So z = 1 + 2 = 3
print(z)
3
In [17]:
print(x, y, z) #
1 2 3
In [18]:
a, b = 3, 4
In [19]:
print(a)
3
In [20]:
print(b)
4

Assigning multiple variables in a single statement

The entire right hand side is evaluated before assigning values to the variables on the left

In [21]:
a, b = b, a
print(a, b)
4 3

Modules

In [22]:
print(pi) # pi does not yet exist
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-22-4f53fd231a03> in <module>()
----> 1 print(pi) # pi does not yet exist

NameError: name 'pi' is not defined
In [23]:
import math # Make the functions and variables in the math module available with the prefix .math
In [24]:
math.pi # pi is now available with the .math prefix
Out[24]:
3.141592653589793
In [25]:
math.sin(1) # sin is a function in the math module
Out[25]:
0.8414709848078965
In [26]:
math.cos(0) # cos is also a function in the math module
Out[26]:
1.0
In [27]:
from math import pi # import the variable pi
In [28]:
pi # pi can now be used without the math. prefix
Out[28]:
3.141592653589793
In [29]:
from math import * # import all variables and functions from the math module
In [30]:
atan(1.0) # atan returns the arctan
Out[30]:
0.7853981633974483
In [31]:
atan2(-1, 1) # atan2 takes the (x, y) coordinates of a point
Out[31]:
-0.7853981633974483
In [32]:
floor(4.3) # floor rounds down to the nearest integer
Out[32]:
4
In [33]:
ceil(4.3) # ceil rounds up to the nearest integer
Out[33]:
5
In [34]:
print(dir(math)) # dir returns a list of all functions and variables in a module
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
In [35]:
? degrees # Get help on a function
In [36]:
help(degrees) # Another way to get help.
Help on built-in function degrees in module math:

degrees(...)
    degrees(x)
    
    Convert angle x from radians to degrees.

In [37]:
degrees(pi) # degrees converts radians to degrees
Out[37]:
180.0

Boolean expressions

Python has a built-in "boolean" data type that can take the values True or False.

A "boolean expression" is a Python statement that evaluates to True or False

Comparison operators

In [38]:
3 == 2
Out[38]:
False
In [39]:
3 == 3
Out[39]:
True
In [40]:
3 != 2
Out[40]:
True
In [41]:
3 != 3
Out[41]:
False
In [42]:
3 > 3
Out[42]:
False
In [43]:
3 >= 3
Out[43]:
True
In [44]:
2 < 1
Out[44]:
False
In [45]:
2 <= 1
Out[45]:
False
In [46]:
If # Variables, function names and keywords are all case-sensitive in Python. So "If" and "if" are not the same.
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-46-53daa6b89a4d> in <module>()
----> 1 If # Variables, function names and keywords are all case-sensitive in Python. So If and if are not the same.

NameError: name 'If' is not defined

"if" statements

These have the syntax:

if <boolean expression>:
    <code to execute if boolean expression is True>
<following code always gets executed>
In [47]:
if 3 > 2:
    print("3 is greater than 2")
3 is greater than 2
In [48]:
3 > 2
Out[48]:
True
In [49]:
if 3 < 2:
    print("3 is less than 2")
In [50]:
3 < 2
Out[50]:
False

"if - else" statements

These have the syntax:

if <boolean expression>:
    <code to execute if boolean expression is True>
else:
    <code to execute if boolean expression is False>
In [51]:
if 3 > 2:
    print("3 is greater than 2")
else:
    print("3 is less than or equal to 2")
3 is greater than 2
In [52]:
if 3 < 2:
    print("3 is less than 2")
else:
    print("3 is greater than or equal to 2")
3 is greater than or equal to 2
In [53]:
if b < a:
    a = a - b
else:
    b = b - a

"if - elif - else" statements

These have the syntax:

if <boolean expression 1>:
    <code to execute if boolean expression 1 is True>
elif <boolean expression 2>:
    <code to execute if boolean expression 2 is True>
    ...
else:
    <code to execute if none of the boolean expressions is True>
In [54]:
color = 'r'
In [55]:
if color == 'g':
    print('green')
elif color == 'r':
    print('red')
else:
    print('blue')
red

"while" statements

These have the syntax:

while <boolean expression>:
    <code to execute while boolean expression is True>
In [56]:
n = 10
while n > 0:
    print(n)
    n -= 1
print("Blast off!")
10
9
8
7
6
5
4
3
2
1
Blast off!
In [57]:
n # n has the final value assigned to it before the while loop terminated
Out[57]:
0

Comments

Anything after a # on the same line is ignored

In [58]:
# This is a comment
In [59]:
print(1)
# comment is ignored
print(2)
1
2

Defining functions

The syntax is:

def <function name>(<parameter list>):
    "Optional documentation string"
    <function code>

The "return" statement inside a function terminates the function, and returns the given value

In [60]:
def add(x, y):
    "Adds x and y"
    return x + y
In [61]:
add(10, 20) # Calling the "add" function with x = 10, y = 20
Out[61]:
30
In [62]:
z = add(10, 20) # z gets assigned the value returned from "add"
In [63]:
z
Out[63]:
30
In [64]:
def add2(x, y):
    "Adds x and y"
    print(x + y) # "print" prints a value to the screen, but doesn't return it
In [65]:
add2(10, 20)
30
In [66]:
w = add2(10, 20)
30
In [67]:
w # "add2" doesn't return a value, so w doesn't get assigned a value
In [68]:
print(w)
None

Logical operations

These are evaluated in the order of precedence:

  • not
  • and
  • or
In [69]:
not 10 == 20
Out[69]:
True
In [70]:
6 < 5 and 2 < 3
Out[70]:
False
In [71]:
6 < 5 or 2 < 3
Out[71]:
True
In [72]:
6 != 5 or 5 > 4 and 4 == 3
Out[72]:
True
In [73]:
not 3 < 2 or 3 > 2
Out[73]:
True
In [74]:
not (3 < 2 or 3 > 2)
Out[74]:
False

Comparison operators can be "chained" to check if a number is in an interval

In [75]:
x = 2
1 < x < 3
Out[75]:
True
In [76]:
1 < x and x < 3 # This is equivalent to 1 < x < 3
Out[76]:
True

Order of precedence for mathematical operations

PEMDAS, just like high school:

  • Parentheses
  • Exponents
  • Multiple/divide
  • Add/subtract
In [77]:
3 + 6**2 # Exponents get evaluated first
Out[77]:
39
In [78]:
(3 + 6)**2 # Use parentheses to manually control the order of operation
Out[78]:
81