Jupyter Snippet P4M 01

Jupyter Snippet P4M 01

All of these python notebooks are available at https://gitlab.erc.monash.edu.au/andrease/Python4Maths.git

Getting started

Python can be used like a calculator. Simply type in expressions to get them evaluated.

Basic syntax for statements

The basic rules for writing simple statments and expressions in Python are:

  • No spaces or tab characters allowed at the start of a statement: Indentation plays a special role in Python (see the section on control statements). For now simply ensure that all statements start at the beginning of the line.
  • The ‘#’ character indicates that the rest of the line is a comment
  • Statements finish at the end of the line:
    • Except when there is an open bracket or paranthesis:
1+2
+3  #illegal continuation of the sum
(1+2
             + 3) # perfectly OK even with spaces
  • A single backslash at the end of the line can also be used to indicate that a statement is still incomplete
1 + \
   2 + 3 # this is also OK

The jupyter notebook system for writting Python intersperses text (like this) with Python statements. Try typing something into the cell (box) below and press the ‘Run’ button above to execute it. We will discuss operators that can be used in such operations further below, but for numbers these are mostly fairly obvious.

1 + 2 * 3
7

Python has extensive help built in. You can execute help() for an overview or help(x) for any library, object or type x. Try using help("topics") to get a list of help pages built into the help system.

help("topics")
Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DELETION            LOOPING             SHIFTING
ASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SLICINGS
ATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SPECIALATTRIBUTES
ATTRIBUTES          DYNAMICFEATURES     METHODS             SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS            MODULES             SPECIALMETHODS
BASICMETHODS        EXCEPTIONS          NAMESPACES          STRINGMETHODS
BINARY              EXECUTION           NONE                STRINGS
BITWISE             EXPRESSIONS         NUMBERMETHODS       SUBSCRIPTS
BOOLEAN             FLOAT               NUMBERS             TRACEBACKS
CALLABLEMETHODS     FORMATTING          OBJECTS             TRUTHVALUE
CALLS               FRAMEOBJECTS        OPERATORS           TUPLELITERALS
CLASSES             FRAMES              PACKAGES            TUPLES
CODEOBJECTS         FUNCTIONS           POWER               TYPEOBJECTS
COMPARISON          IDENTIFIERS         PRECEDENCE          TYPES
COMPLEX             IMPORTING           PRIVATENAMES        UNARY
CONDITIONAL         INTEGER             RETURNING           UNICODE
CONTEXTMANAGERS     LISTLITERALS        SCOPING             
CONVERSIONS         LISTS               SEQUENCEMETHODS     
DEBUGGING           LITERALS            SEQUENCES           

Variables & Values

A name that is used to denote something or a value is called a variable. In python, variables can be declared and values can be assigned to it as follows,

x = 2          # anything after a '#' is a comment
y = 5
xy = 'Hey'
print(x+y, xy) # not really necessary as the last value in a bit of code is displayed by default
7 Hey

Multiple variables can be assigned with the same value.

x = y = 1
print(x,y)
1 1

The basic types build into Python include float (floating point numbers), int (integers), str (unicode character strings) and bool (boolean). Some examples of each:

2.0           # a simple floating point number
1e100         # a googol as floating point number
-1234567890   # an integer
True or False # the two possible boolean values
'This is a string'
"It's another string"
print("""Triple quotes (also with '''), allow strings to break over multiple lines.
Alternatively \n is a newline character (\t for tab, \\ is a single backslash)""")
Triple quotes (also with '''), allow strings to break over multiple lines.
Alternatively 
 is a newline character (	 for tab, \ is a single backslash)

Python also has complex numbers that can be written as follows. Note that the brackets are required.

complex(1,2)
(1.0+2j) # the same number as above
(1+2j)

Operators

Arithmetic Operators

Symbol Task Performed
+ Addition
- Subtraction
/ Division
// Integer division
% Modulus (remainder)
* Multiplication
** Exponentiation (power)

As expected these operations generally promote to the most general type of any of the numbers involved i.e. int -> float -> complex.

1+2.0
3.0
3-1
2
2 * (3+0j) * 1.0
(6+0j)
3/4
0.75

In many languages (and older versions of python) 1/2 = 0 (truncated division). In Python 3 this behaviour is captured by a separate operator that rounds down: (ie a // b$=\lfloor \frac{a}{b}\rfloor$)

3//4.0
0.0
15%10
5

Python natively allows (nearly) infinite length integers while floating point numbers are double precision numbers:

11**300
2617010996188399907017032528972038342491649416953000260240805955827972056685382434497090341496787032585738884786745286700473999847280664191731008874811751310888591786111994678208920175143911761181424495660877950654145066969036252669735483098936884016471326487403792787648506879212630637101259246005701084327338001
11.0**300
---------------------------------------------------------------------------

OverflowError                             Traceback (most recent call last)

<ipython-input-14-b61ab01789ad> in <module>
----> 1 11.0**300


OverflowError: (34, 'Numerical result out of range')

Relational Operators

Symbol Task Performed
== True, if it is equal
!= True, if not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

Note the difference between == (equality test) and = (assignment)

z = 2
z == 2
True
z > 2
False

Comparisons can also be chained in the mathematically obvious way. The following will work as expected in Python (but not in other languages like C/C++):

0.5 < z <= 1
False

Boolean and Bitwise Operators

Operator Meaning | Symbol Task Performed
and Logical and | & Bitwise And
or Logical or | $\mid$ Bitwise OR
not Not | ~ Negate
    | ^ Exclusive or
    | » Right shift
    | « Left shift
a = 2 #binary: 10
b = 3 #binary: 11
print('a & b =',a & b,"=",bin(a&b))
print('a | b =',a | b,"=",bin(a|b))
print('a ^ b =',a ^ b,"=",bin(a^b))
print('b << a =',b<<a,"=",bin(b<<a))
a & b = 2 = 0b10
a | b = 3 = 0b11
a ^ b = 1 = 0b1
b << a = 12 = 0b1100
print( not (True and False), "==", not True or not False)
True == True

Assignment operators

The binary operators can be combined with assignment to modify a variable value. For example:

x = 1
x += 2 # add 2 to x
print("x is",x)
x <<= 2 # left shift by 2 (equivalent to x *= 4)
print('x is',x)
x **= 2 # x := x^2
print('x is',x)
x is 3
x is 12
x is 144

Built-in Functions

Python comes with a wide range of functions. However many of these are part of stanard libraries like the math library rather than built-in.

Converting values

Conversion from hexadecimal to decimal is done by adding prefix 0x to the hexadecimal value or vice versa by using built in hex( ), Octal to decimal by adding prefix 0 to the octal value or vice versa by using built in function oct( ).

hex(171) # hexadecmial value as string
'0xab'
0xAB
171

int( ) converts a number to an integer. This can be a single floating point number, integer or a string. For strings the base can optionally be specified:

print(int(7.7), int('111',2),int('7'))
7 7 7

Similarly, the function str( ) can be used to convert almost anything to a string

print(str(True),str(1.2345678),str(-2))
True 1.2345678 -2

Mathematical functions

Mathematical functions include the usual suspects like logarithms, trigonometric fuctions, the constant $\pi$ and so on.

import math
math.sin(math.pi/2)
from math import * # avoid having to put a math. in front of every mathematical function
sin(pi/2) # equivalent to the statement above
1.0

Simplifying Arithmetic Operations

round( ) function rounds the input value to a specified number of places or to the nearest integer.

print( round(5.6231) )
print( round(4.55892, 2) )
6
4.56

abs( ) provides the absolute value of any number (including the magnitude of a complex number).

c =complex('5+2j')
print("|5+2i| =", abs(c) , "\t |-5| =", abs(-5) )
|5+2i| = 5.385164807134504 	 |-5| = 5

divmod(x,y) outputs the quotient and the remainder in a tuple (you will be learning about tuples in the further chapters) in the format (quotient, remainder).

divmod(9,2)
(4, 1)

Accepting User Inputs

input(prompt), prompts for and returns input as a string. A useful function to use in conjunction with this is eval() which takes a string and evaluates it as a python expression.

Note: In notebooks it is often easier just to modify the code than to prompt for input.

abc =  input("abc = ")
abcValue=eval(abc)
print(abc,'=',abcValue)
abc = 2 + 3*4
2 + 3*4 = 14