Numbers in Python

Numbers in Python

by David Amos Reading time estimate 34m basics python

You don’t need to be a math whiz to program well. The truth is, few programmers need to know more than basic algebra. Of course, how much math you need to know depends on the application you’re working on. In general, the level of math required to be a programmer is lower than you might expect. Although math and computer programming aren’t as correlated as some people might believe, numbers are an integral part of any programming language, and Python is no exception.

In this tutorial, you’ll learn how to:

  • Create integers and floating-point numbers
  • Round numbers to a given number of decimal places
  • Format and display numbers in strings

Let’s get started!

Integers and Floating-Point Numbers

Python has three built-in numeric data types: integers, floating-point numbers, and complex numbers. In this section, you’ll learn about integers and floating-point numbers, which are the two most commonly used number types. You’ll learn about complex numbers in a later section.

Integers

An integer is a whole number with no decimal places. For example, 1 is an integer, but 1.0 isn’t. The name for the integer data type is int, which you can see with type():

Language: Python
>>> type(1)
<class 'int'>

You can create an integer by typing the desired number. For instance, the following assigns the integer 25 to the variable num:

Language: Python
>>> num = 25

When you create an integer like this, the value 25 is called an integer literal because the integer is literally typed into the code.

You may already be familiar with how to convert a string containing an integer to a number using int(), which is especially useful when working with user input. For example, the following converts the string "25" to the integer 25:

Language: Python
>>> int("25")
25

int("25") is not an integer literal because the integer value is created from a string.

When you write large numbers by hand, you typically group digits into groups of three separated by a comma or a decimal point. The number 1,000,000 is a lot easier to read than 1000000.

In Python, you can’t use commas to group digits in integer literals, but you can use underscores (_). Both of the following are valid ways to represent the number one million as an integer literal:

Language: Python
>>> 1000000
1000000

>>> 1_000_000
1000000

There’s no limit to how large an integer can be, which might be surprising considering that computers have a finite amount of memory. Try typing the largest number you can think of into IDLE’s interactive window. Python can handle it with no problem!

Floating-Point Numbers

A floating-point number, or float for short, is a number with a decimal place. 1.0 is a floating-point number, as is -2.75. The name of the floating-point data type is float:

Language: Python
>>> type(1.0)
<class 'float'>