02. Numbers: Integers, Longs, Floats and Complex

There are several types of numbers in the Python programming language. Their uses depend on the context of the problem.

Integers

The first are integers. Here, we have a whole number that may be preceeded by a plus or minus sign.

> 2
2
> -3
-3 

Floating points (aka floats)

These values are equivalent to scientific notation. They are made up of digits, and an e followed by an exponent.

> 2e4
200000.0
> 4e-3
0.004
> 0.0000001
1e-07

Hexadecimal

You may also specify numbers in hexadecimal notation, using base 16 instead of base 10. For values from 10 to 16, use letters A to F.

> 0x3F   # (3 x 16) + (15 * 1)
63
> 0xFFFFFF 
16777215

Typecasting

So what happens if you combine two numbers of different type? If you try it out, you can see that our result will be of the type that carries more precision. Thus, if we add a float and an int, we obtain a float.

> 3.4//3
1.0  # Floored, but still a float.

Imaginary/Complex Numbers

We may represent imaginary numbers by adding either a j or J to our expression.

> 5+3j
(5+3j)

Typecasting

So what happens if you combine two numbers of different type? If you try it out, you can see that our result will be of the type that carries more precision. Thus, if we add a float and an int, we obtain a float.

> 3.4//3
1.0  # Floored, but still a float.

Useful functions

Here are some useful functions that can be used with numbers.

abs(val)
Absolute value of number.
max(val)
Maximum of a set of numbers.
min(val)
Minimum of a set of numbers.
int(val)
Convert number (or string) to an integer.
float(val)
Convert number (or string) to a float.
bool(val)
Convert to a boolean.
0 is False, all else is True.
str(val)
Convert to a string.

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Programming Python

Learn to be a Pythonista! Try Python

Programming Python shows in-depth tutorials on the language's number of application domains including: system administration, GUIs, the Web, networking, front-end scripting layers, and more. This book focuses on commonly used tools and libraries to give you a comprehensive understanding of Python’s many roles in practical, real-world programming.

$ Check price
64.9964.99Amazon 4 logo(56+ reviews)

More Python resources

Ad