mkaz.blog

Working with Python

Numbers

Convert string to integer

You must explicitly convert strings to integers, use the int() function to convert. You will get a TypeError if you don't convert.

s = '13'
s + 2
>>> TypeError: can only concatenate str (not "int") to str

Instead use:

s = '13'
int(s) + 2
>>> 15

You need to be aware that the + operator is used for joining strings and lists together, so you might get strange results if you don't convert first.

s = '13'
t = '2'
s + t
>>> '132'

Convert string to float

Use float() to convert a string to a float, or to convert an integer to a float.

n = 23
float(n)
>>> 23.0

Check if string is a number

There is not a simple built-in way to check if a string is a number. You can use .isdigit() and .isnumeric() but they will fail on negative and decimal. This function is probably your best option:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Modulo Arithmetic

For Python, use the // to get the floored quotient (the whole number in division) and % to get the remainder. For example:

13 // 4
>>> 3
 
13 % 4
>>> 1

Exponent Arithmetic

There are two ways to do power of math, use the ** operator or the pow() function, they will give the same results:

4 ** 2
>>6 16
 
pow(4, 2)
>>> 16

Absolute Value

Use the abs() function to get the absolute value for a number

abs(-3)
>>> 3

Sum Numbers in a List

Python has a built-in function to sum elements in a list.

set = [1, 2, 3]
sum(set)
>>> 6

Underscores for Long Numbers

You can use underscores in long numbers to make them easier to read. They are ignored by the interpreter.

x = 100000000
y = 100_000_000   # like commas
z = 10_00_0_0000  # weird
x == y == z
>>> True

If you want to format a number with commas for display, use {:,} format. See my string formatting page for many examples on formatting.

y = 100_000_000
print(f"{y:,}")