Expressions and data types

By Martin McBride, 2018-04-05


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)
If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest