Skip to content

Builtins

Converting between types

Text from the keyboard (input()) always arrives as a string. To use user input in calculations, you must first convert it to numbers.

The built-in int() function takes a string, decimal or boolean (True or False) and tries to convert it into a integer.

float() does the same for decimals.

>>> year_of_birth = input("Please enter the year you were born: ")
Please enter the year you were born: 2006
>>> print("You were born", 2026 - int(year_of_birth), "years ago")
You were born 20 years ago

If int() is unable to convert the input, it produces a ValueError.

>>> int('abc')  # 'abc' does not represent any valid number in base-10
ValueError ...
>>> int('abc', 16)  # 'abc' is a valid hex number, i.e. base-16
2748
>>> int("3.5")  # does not allow a dot in the string. use `float()`
ValueError ...

Converting a decimal to an integer truncates the decimal part:

>>> int(3.5)
3

Python converts all operands of an arithmetic expression to float if any one operand is a decimal:

>>> 3 + 1.0
4.0

round() and abs()

Use built-in round() to control the precision of decimal values:

>>> round(1 / 3)
0
>>> round(1 / 3, 2)
0.33

Use the built-in abs() to ensure a number is positive:

>>> abs(-7)
7
>>> abs(0.5)
0.5

ord and chr

ord converts a character into its ASCII numeric value:

>>> ord('a')
97
>>> ord('A')
65

chr() converts in the opposite direction. So:

>>> print(chr(104) + chr(101) + chr(108) + chr(108) + chr(111))
hello