# Expressions and data types

05 Apr 2018## Numbers

```
#
# Types of numbers
#
5 # -> 5 (integer)
type(5) # -> <class 'int'>
# integer type
2.5 # -> 2.5 (float)
type(2.5) # -> <class 'float'>
# floating point type
10**100 # -> 10000000000000000000000000000...000
# eg 10 to the power 100 is 1 followed by 100 zeros
# integers can have any number of digits,
1/3 # -> 0.3333333333333333
# Floats have around 16 significant figures
2+3j # -> (2+3j) (complex number, j represents
# imaginary number)
type(2+3j) # -> <class 'complex'>
# complex number type
```

## Maths

```
#
# Operators
#
2 + 4 # -> 6 (addition)
7 - 3 # -> 4 (subtraction)
6 * 2 # -> 12 (multiplication)
5 / 2 # -> 2.5 (division)
2**3 # -> 8 (raise to the power, 2 to the power 3)
(4 + 3) * 2 # -> 24 (brackets change priority)
5 // 2 # -> 2 (integer division always rounds down)
-5 // 2 # -> -3
5 % 2 # -> 1 (modulo or remainder)
5.7 // 2.1 # -> 2.0 ( // works with floats,
# always a whole number)
5.7 % 2.1 # -> 1.5
# % also works with floats, result is:
# x % y = x - y * (x // y)
#
# int or float result?
#
2.0 + 3 # -> 5.0 (if any input is a float,
# the result will be a float)
2 + 3 # -> 5 (if all inputs are ints the
# result will be an int)
# EXCEPT:
6 / 3 # -> 2.0 (division always gives a float
# even if the result is a whole number)
2**-2 # -> 0.25 (raising to a negative power
# always gives a float)
```

## Variables

```
a = 3 # variables don't need to be declared
b = 1.2 # they are created when first assigned
type(a) # -> <class 'int'>
# variables don's have a type, but data does
a = 2.5 # the same variable can be assigned different data types
type(a) # -> <class 'float'>
a = 'abc' # -> <class 'str'> see below
type(a) # -> <class 'str'> see below
xyz = 0 # variable names must start with a letter or
my_val3 =1 # underscore, and may also contain numbers (but
_a30 = 30 # not as the first character)
alpha = 2 # by convention they only use lower case letters
PI = 3.14 # or uppercase letters to indicate that they are
# intended to be constant (Python doesn't actually
# prevent these values from being altered)
```

## String type

```
'abc' # -> 'abc' (a text string)
"abc" # -> 'abc' (double or single quotes are allowed)
```

## Conversions

```
int(3.7) # -> 3 (converts a float to an int)
int(-3.7) # -> -3 (fractional part is truncated)
int('12') # -> 12 (converts strings too)
float(3) # -> 3.0 (converts an int to a float)
float('1.5') # -> 1.5 (converts strings too)
complex(1, 2) # -> (1+2j) (2 numbers to a complex number)
complex('1+2j') # -> (1+2j) (converts strings too)
complex('1 + 2j') # -> ERROR (spaces not allowed)
str(3) # -> '3' (converts to string)
str(1.5) # -> '1.5' (converts to string)
str(1+2j) # -> '(1+2j)' (converts to string)
```