Information
Section: Syntax and arithmetic
Goal: Understand the basics of the syntax in Python.
Time needed: 20 min
Prerequisites: Curiosity
Syntax and arithmetic¶
Credits: Institute of Maritime Logistics – Hamburg University of Technology
1 Getting started ¶
Python can be used like a calculator. This module will cover the correct syntax expressions to evaluate and perform various operations using Python.
Basic syntax for statements ¶
The basic rules for writing simple statements 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) and can cause issues when compiling or executing code. 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 parenthesis:
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 combines text (like this) with Python statements. Try typing something into the cell (box) below and press the ‘run cell’ button above (triangle+line symbol) to execute it.
1+2+3+4
10
Python has extensive help built in for any questions your have that are not covered in these modules. You can execute help() for an overview or help(x) for any library, object or type x to get more information. For example: (uncomment the line by removing the #
to run the cell)
#help()
2 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 '#' is a comment
y = 5 # 'y' is the variable while 5 is the value
xy = 'Hey' # variables can be text as well as numbers
print(x+y, xy) # print() can be used to display the values/outputs of the variables specified
7 Hey
Multiple variables can be assigned with the same value.
x = y = 1
print(x,y) # not really necessary as the last value in a bit of code is displayed by default
1 1
The basic data types that are built 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, the "e" denotes the number beforehand muliplied by 10 to the power of the number following it
-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)
3 Operators ¶
3.1 Arithmetic Operators ¶
These symobols denote what keystroke to use for arithmetic operators.
Symbol |
Task Performed |
---|---|
+ |
Addition |
- |
Subtraction |
/ |
division |
% |
mod (finds remainder after division) |
* |
multiplication |
// |
floor division (rounds to nearest significant digit) |
** |
to the power of |
1+2
3
2-1
1
1*2
2
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\))
print(3/4)
print(3//4)
0.75
0
15%10
5
Python natively allows (nearly) infinite length integers while floating point numbers are double precision numbers:
11**30
17449402268886407318558803753801
11.0**30
1.7449402268886406e+31
3.2 Relational Operators ¶
These operators return True or False depending on the validity of the statement made.
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:
0.5 < z <= 1
False
3.3 Boolean ¶
Boolean expressions are used to combine several requirements which need to be fulfilled.
If you query a database at a library and you look for articles which include “cloning”, “humans”, and “ethics”, this connection narrows you down to less books.
You would connect the terms with an and
.
If you on the other side connect the same search terms with an or
, you broaden the results.
3.4 Regular Operators ¶
Regular operators are used to connect Boolean values, i.e. True and False.
If one of the values is not Boolean, the value is treated as one.
For this a very specific behavior is used, e.g. the number 0
is treated as False while e.g. the number 42
treated as True.
More information on how non-Boolean values are interpreted once you connect them with and
or or
can be found here
3.5 Bitwise Operators ¶
Bitwise operators breakdown the statements to their binary representation of the data then assess it. Some libraries, such as the library “pandas”, have overwritten that behavior with their own logic.
Meaning |
Regular Operator |
Boolean Bitwise Operator |
---|---|---|
Logical and |
|
& |
Logical or |
|
\(\mid\) |
Negation |
|
~ |
Boolean operators can be used in conjunction.
A not
converts True and False to the opposite meaning, True becomes False and False becomes True.
An and
takes two terms and is evaluated as False unless the two terms are both True.
Finally, an or
takes two terms and always evaluates to True unless the two terms are both False.
See more here
not True, True and True, True and False, True or False
(False, True, False, True)
not (True and False), "==", not True or not False
(True, '==', True)
4 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. Libraries are pre written code created by other Python users that create subroutines and add functionality to Python.
Since Python is constantly evolving, so are its libraries, here is a list of some commonly used libraries in 2018: https://bit.ly/2udZeow
4.1 Converting values ¶
Conversions from one data form to another, i.e. a integer to string, can be done by various commands because Python considers string ‘7’ and float ‘7.0’ two different things and they cannot be used interchangeably.
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
4.2 Mathematical functions ¶
Mathematical functions include the usual suspects like logarithms, trigonometric fuctions, the constant \(\pi\) and so on. math
is a library that can be imported into Phython as mentioned before:
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
4.3 Simplifying Arithmetic Operations ¶
round( ) function rounds the input value to a specified number of places or to the nearest integer.
round(5.6231)
6
round(4.55892, 2)
4.56