Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 2 – Values, variables, numbers and strings

Integers, floats and arithmetic operators

Use Python's arithmetic operators on int and float: true and floor division, % with negative numbers, ** and divmod(), huge integers and round().

  • Beginner
  • 20 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Predict whether a number literal makes an int or a float
  • Use +, -, *, /, //, % and ** with integers and floats, and predict the type of each result
  • Predict // and % results for negative numbers
  • Explain arbitrary-precision integers and the integer string-conversion limit
  • Choose between round(), int(), math.floor() and math.ceil() when a result must be a whole number

Before you start

What you’ll learn · Before you start

What you will learn

  • Predict whether a number literal makes an int or a float
  • Use +, -, *, /, //, % and ** with integers and floats, and predict the type of each result
  • Predict // and % results for negative numbers
  • Explain arbitrary-precision integers and the integer string-conversion limit
  • Choose between round(), int(), math.floor() and math.ceil() when a result must be a whole number

Before you start

On this page

Ask Python for -7 // 2 and it answers -4, where Java answers -3; ask it for 17 / 5 and you get the float 3.4, although both numbers are ints. Python has two number types for everyday work. An int is a whole number such as 42, -7 or 0, and it can be as large as your computer’s memory allows. A float is a number with a fractional part, such as 3.5 or 0.25, stored in binary with 53 bits of precision, which is roughly 16 significant decimal digits. (A third type, complex, for numbers such as 3+4j, is for maths and engineering; the later lesson on the math module comes back to it.)

This lesson covers the operators that do arithmetic with both, and the few places where they behave differently from a pocket calculator. You will predict the type of every result, work out // and % for negative numbers, split amounts into units with divmod() and choose how a result becomes a whole number.

How you write a number decides its type

Number literals Python · literals.py
print(1_000_000)  # underscores make long numbers easier to read
print(0b1010, 0o17, 0xFF)  # binary, octal and hexadecimal literals
print(2e3, 1.5e-3)  # e notation always gives a float
print(type(2e3), type(2_000))

Output

1000000
10 15 255
2000.0 0.0015
<class 'float'> <class 'int'>

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 literals.py

  • Underscores between digits are ignored, so 1_000_000 is easier to read than 1000000 and means the same (PEP 515, Python 3.6). Only single underscores between digits are allowed: 1__000 and 1000_ are syntax errors.
  • 0b, 0o and 0x start binary, octal and hexadecimal numbers. A later lesson on number bases covers them.
  • A decimal point or an e makes a float. 2e3 means 2 × 10³, and it is the float 2000.0, not the int 2000.
  • A whole number other than zero cannot start with 0: 017 is a SyntaxError, and the message suggests the 0o prefix in case you meant octal. Phone numbers, PIN codes and other identifiers with leading zeros are text, not numbers; keep them as strings.

Each of these is a literal: A value written straight into the code, such as 42, 3.5, 0xFF or "text". How a number literal is written decides its type; a decimal point or an e makes a float., a value written straight into the code. Python reads the whole file before it runs any of it, so a literal it cannot read stops the program at once. Press Edit, change 1_000_000 on the first line to 1__000 and run the program: it stops with a SyntaxError before it prints anything at all.

Checkpoint

Check: Number literals

  1. Question 1 of 2 Which of these literals makes a float?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 2e3

    A decimal point or an e makes a float; underscores, prefixes such as 0x and plain digits make ints. 2e3 is the float 2000.0, and the other three are the int 2000.

  2. Question 2 of 2 A form collects a four-digit PIN such as 0427. Why should the program keep it as a string?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: int() of the text gives 427 and loses the leading zero, and a PIN is an identifier, not an amount

    A number has no leading zeros, so converting a PIN, a phone number or a roll number to an int changes it. Keep identifiers as text and convert only values you calculate with.

Every operator has a rule for the type it returns

  • +, - and * add, subtract and multiply: 17 * 5 gives 85.
  • / divides, and the result is always a float: 17 / 5 gives 3.4.
  • // divides and then rounds down to a whole number (floor division: Division that rounds down to a whole number, towards minus infinity, written //. 17 // 5 is 3, and -7 // 2 is -4.): 17 // 5 gives 3.
  • % gives the remainder that floor division leaves (modulo: The remainder that floor division leaves, written %. 17 % 5 is 2; in Python the remainder takes the sign of the divisor, so -7 % 3 is 2.): 17 % 5 gives 2.
  • ** raises to a power: 17 ** 2 gives 289.
Every arithmetic operator once Python · arithmetic_tour.py
a, b = 17, 5
print(a + b, a - b, a * b)
print(a / b)  # true division: always a float
print(a // b)  # floor division
print(a % b)  # the remainder
print(a ** 2)  # a power

print(10 / 2)  # a float, even when the division is exact
print(3 * 1.5, 2 + 0.0)  # an int and a float give a float
print(2 ** 0.5, 2 ** -1)  # fractional and negative powers give floats
print(2 ^ 3)  # careful: ^ is not a power in Python

Output

22 12 85
3.4
3
2
289
5.0
4.5 2.0
1.4142135623730951 0.5
1

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 arithmetic_tour.py

Three rules explain every result above:

  1. / always gives a float, even when the division comes out exact: 10 / 2 is 5.0. Use // when you need a whole number.
  2. An int and a float give a float. Python converts the int first, so 3 * 1.5 is 4.5 and 2 + 0.0 is 2.0. Two ints give an int with +, -, *, //, % and **, except that a negative power gives a float: 2 ** -1 is 0.5.
  3. ** is the power operator. ^ also exists, but it is the bitwise “exclusive or” of the two numbers’ bits, so 2 ^ 3 is 1, not 8. Spreadsheet formulas write powers with ^, which makes this an easy mistake.

A common mistake: / where a whole number is needed

A list position must be an int. A float from / is not one, even when it happens to be 2.0:

The middle of a list Python · middle_item.py
names = ["Asha", "Ben", "Chen", "Dev", "Esi"]
middle = len(names) / 2
print(middle)
print(names[middle])

Output (exit status 1)

2.5

Printed as an error (standard error)

Traceback (most recent call last):
  File "middle_item.py", line 4, in <module>
    print(names[middle])
          ~~~~~^^^^^^^^
TypeError: list indices must be integers or slices, not float

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 middle_item.py

len(names) // 2 gives 2, and names[2] is "Chen". When the length is even, // picks the second of the two middle positions; decide whether that is what you want.

Checkpoint

Check: Operators and the type of their results

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(2 ^ 3)
    Show the answer: Question 1 of 2

    Answer: 1

    ** is the power operator; ^ is the bitwise "exclusive or". 0b10 ^ 0b11 is 0b01, so the program prints 1.

  2. Question 2 of 2 names has 6 items. Which expression picks one of its middle items?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: names[len(names) // 2]

    / always gives a float, even when the division is exact, and lists take only int positions. // gives the int 3, so names[3] is one of the two middle items.

Floor division rounds down, even for negative numbers

a // b does the division and then rounds down, towards minus infinity. For positive numbers that simply drops the fraction, but for a negative result it is one less than you might expect: -7 / 2 is -3.5, so -7 // 2 is -4. Many languages, Java among them, round integer division towards zero instead and would give -3; rounding towards zero is called truncation: Rounding towards zero by dropping the fractional part, as int() does. int(-3.99) is -3; Java's integer division truncates too.. The number line shows the two directions for -3.5:

A number line from -4 to 0 with -3.5 marked: floor division moves it down to -4, and int() of -7 / 2 moves it towards zero, to -3.-7 / 2 is -3.5-7 // 2 → -4floor: always down-4-3.5-3-2-10int(-7 / 2) → -3truncation: towards zero

Two ways to make a whole number of -3.5

Text description of the diagram

A number line shows the whole numbers -4, -3, -2, -1 and 0, with the exact result of -7 / 2, which is -3.5, marked between -4 and -3.

  • Above the line, an arrow goes from -3.5 to the left, to -4: floor division, -7 // 2, always rounds down, towards minus infinity.
  • Below the line, an arrow goes from -3.5 to the right, to -3: int(-7 / 2) drops the fraction, which moves the value towards zero. Java, for example, rounds its integer division this way.

For positive results the two agree: 7 // 2 and int(7 / 2) are both 3.

a % b is whatever floor division leaves over, so the two are tied together by one rule that always holds for ints: a == b * (a // b) + a % b. A consequence is that the remainder has the same sign as b, the number you divide by, or is 0:

// and % for every combination of signs Python · floor_and_remainder.py
print(" a   b  a // b  a % b  check")
for a in (7, -7):
    for b in (2, -2):
        check = b * (a // b) + a % b  # always gives a back
        print(f"{a:2}  {b:2}  {a // b:6}  {a % b:5}  {check:5}")

print(divmod(-7, 2))  # both results at once: (a // b, a % b)

Output

 a   b  a // b  a % b  check
 7   2       3      1      7
 7  -2      -4     -1      7
-7   2      -4      1     -7
-7  -2       3     -1     -7
(-4, 1)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 floor_and_remainder.py

Read the rows as predictions you can check. The check column works out b * (a // b) + a % b, and it gives back a every time. divmod(a, b) returns both results at once, as the pair (a // b, a % b).

Key idea

// rounds towards minus infinity and % is what it leaves, so a == b * (a // b) + a % b holds for every pair of ints, and with a positive divisor the remainder is never negative.

Why rounding down is useful

With a positive divisor, % never returns a negative number, so it is ideal for anything that wraps around, such as days of the week. And divmod(), which gives the quotient and the remainder together, is the natural tool for splitting an amount into units. Step through both uses and watch the variables:

Interactive · line by line Wrapping round a week and splitting seconds Step through the program. The first lines find days of the week with %, the last ones split 7,384 seconds into hours, minutes and seconds with divmod().

Program · clock_maths.py

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
today = 0  # Monday
print("In 10 days:", days[(today + 10) % 7])
print("3 days ago:", days[(today - 3) % 7])  # -3 % 7 is 4, never negative

total = 7384  # seconds
minutes, seconds = divmod(total, 60)
hours, minutes = divmod(minutes, 60)
print(hours, "h", minutes, "min", seconds, "s")

Variables

After line 9: days is ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; today is 0; total is 7384; minutes is 3; seconds is 4; hours is 2.days'Mon'0'Tue'1'Wed'2'Thu'3'Fri'4'Sat'5'Sun'6today0total7384minutes3seconds4hours2
  • changed in this step

Printed so far

In 10 days: Thu
3 days ago: Fri
2 h 3 min 4 s

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 9 steps are listed below.

Line run 9
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] makes days a list of 7 items.
  3. Line 2. today = 0 sets today to 0.
  4. Line 3. print("In 10 days:", days[(today + 10) % 7]) prints In 10 days: Thu. (0 + 10) % 7 is 3, the remainder after one whole week, and position 3 of days holds Thu.
  5. Line 4. print("3 days ago:", days[(today - 3) % 7]) prints 3 days ago: Fri. Key point (0 - 3) % 7 is 4, not -3. With a positive divisor the remainder is never negative, so going back past Monday needs no special case.
  6. Line 6. total = 7384 sets total to 7384.
  7. Line 7. minutes, seconds = divmod(total, 60) sets minutes to 123 and sets seconds to 4. divmod(7384, 60) gives the pair (123, 4), 123 whole minutes and 4 seconds left over, and unpacking gives the two parts their names.
  8. Line 8. hours, minutes = divmod(minutes, 60) sets hours to 2 and sets minutes to 3 (it was 123). The same split again turns the 123 minutes into 2 hours and 3 minutes, and minutes is rebound to the remainder.
  9. Line 9. print(hours, "h", minutes, "min", seconds, "s") prints 2 h 3 min 4 s. That was the last line, so the program ends.

Three days before Monday (position 0) is position -3 % 7, which is 4, Friday, with no special case for going back past the start of the week. Python’s programming FAQ gives the same reason for the design: when the divisor is positive, a remainder that is never negative is almost always the one you want.

India-specific

Because Python ignores the underscores in a number, it accepts Indian digit grouping too: 1_00_000 is one lakh and 1_00_00_000 one crore. The , option of Python’s number formatting groups digits in threes, though. Money is safest counted in paise, as an int, and divmod() splits it back into rupees and paise:

Lakhs and paise Python · indian_amounts.py
amount = 1_00_000  # one lakh, grouped the Indian way
print(amount)
print(f"{amount:,}")  # the , option groups digits in threes

rupees, paise = divmod(12_345, 100)  # 12,345 paise
print(rupees, "rupees and", paise, "paise")

Output

100000
100,000
123 rupees and 45 paise

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 indian_amounts.py

Lakh Crore Converter (to Million, Billion) See a number with Indian and international grouping side by side, in words too.

Checkpoint

Check: // and % with negative numbers

  1. Question 1 of 3 What is the value of -17 // 5?

    Type a number.

    A hint

    Work out -17 / 5 first, then round down, not towards zero.

    Show the answer: Question 1 of 3

    Answer: -4

    -17 / 5 is -3.4, and floor division rounds down, towards minus infinity, so the result is -4. Truncation, as in Java or int(-17 / 5), would give -3.

  2. Question 2 of 3 What is the value of -17 % 5?

    Type a number.

    A hint

    Use a == b * (a // b) + a % b with the value of -17 // 5.

    Show the answer: Question 2 of 3

    Answer: 3

    -17 // 5 is -4, and -17 - 5 * (-4) is -17 + 20, which is 3. With a positive divisor the remainder is never negative.

  3. Question 3 of 3 In the clock program, Monday is position 0 of days. Today is Wednesday, today = 2. Which position does (today - 10) % 7 give for the day 10 days ago?

    Type a number.

    Show the answer: Question 3 of 3

    Answer: 6

    2 - 10 is -8, -8 // 7 is -2, and -8 - 7 * (-2) is 6, so the day 10 days before a Wednesday is position 6, a Sunday. The remainder lands in 0 to 6 however far back you go.

Integers have no size limit

In many languages an integer has a fixed size, such as 64 bits, and a calculation that goes past the limit overflows. Python’s ints grow as needed, so adding, subtracting, multiplying, floor-dividing and raising them to powers that are not negative is always exact:

Big integers Python · big_numbers.py
import sys

print(2 ** 100)
print(len(str(2 ** 1000)), "digits in 2 ** 1000")
print(sys.maxsize)  # the largest size a list or a string can have, not the largest int
print(sys.maxsize + 1)  # no overflow: an int simply grows

Output

1267650600228229401496703205376
302 digits in 2 ** 1000
9223372036854775807
9223372036854775808

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 big_numbers.py

sys.maxsize is not the largest int. It is the largest value of Py_ssize_t, the C type CPython uses for the size of a list or a string and for positions in it (PEP 353), and adding 1 to it works like any other addition.

Version note

In your browser, Python runs as 32-bit WebAssembly, so sys.maxsize there is 2147483647 (2³¹ − 1) instead of the 64-bit value 9223372036854775807 (2⁶³ − 1). The int arithmetic itself gives the same results everywhere.

In your browser, Pyodide 314.0.7 (CPython 3.14.2) prints:

1267650600228229401496703205376
302 digits in 2 ** 1000
2147483647
2147483648

The digit limit for converting to text

Python lets you compute with ints of any size, but turning one into decimal digits, with str(), print() or an f-string, or reading digits with int(), takes time that grows faster than the number of digits. A program that accepts a number from a user could be stalled by one with millions of digits, so CPython refuses conversions of more than 4,300 decimal digits by default:

The 4,300-digit limit Python · digit_limit.py
import sys

big = 10 ** 5000  # computing with a huge int is fine
print(big.bit_length(), "bits")

try:  # try and except catch the error so that the program can go on
    text = str(big)  # turning it into decimal text is limited
except ValueError as error:
    print("ValueError:", error)

print(len(hex(big)), "characters in hexadecimal")  # no limit for hex
sys.set_int_max_str_digits(6000)  # raise the limit, for this program only
print(len(str(big)), "decimal digits")

Output

16610 bits
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
4155 characters in hexadecimal
5001 decimal digits

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 digit_limit.py

The try and except lines (the module on errors explains them) catch the ValueError so that the program can go on. Hexadecimal and binary conversions are not limited, and sys.set_int_max_str_digits() raises the limit for the rest of the program, as the last two lines show; 0 would remove it. Raise it only in programs that never convert numbers that come from outside, such as a web form or an uploaded file. Press Edit, change 6000 to 5000 and run the program again: the last conversion, of a number with 5,001 digits, now fails as well.

Big Number Calculator Work out powers and factorials with thousands of digits without writing a program.

Checkpoint

Check: Ints of any size, and the digit limit

  1. Question 1 of 2 What does sys.maxsize + 1 give in CPython on a 64-bit computer?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The int 9223372036854775808, because ints grow as needed

    sys.maxsize is the largest Py_ssize_t, the type CPython uses for sizes and positions. An int can be far larger, so sys.maxsize + 1 is just the next whole number.

  2. Question 2 of 2 x = 10 ** 5000. With the default settings, which of these raises ValueError?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: str(x)

    CPython limits conversions between int and decimal text to 4,300 digits by default, because their cost grows faster than the number of digits. Arithmetic and hexadecimal, octal and binary conversions are unlimited.

round() breaks ties to even, while int() drops the fraction

round(), int() and floor division Python · rounding.py
print(round(2.5), round(3.5), round(-2.5))  # a tie goes to the even neighbour
print(round(2.567, 2), round(1234, -2))  # to 2 decimal places; to the nearest hundred
print(int(3.99), int(-3.99))  # int() drops the fraction
print(-7 // 2, int(-7 / 2))  # floor division and dropping the fraction differ

Output

2 4 -2
2.57 1200
3 -3
-4 -3

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 rounding.py

  • round(x) returns the nearest int, and a tie goes to the even neighbour: round(2.5) is 2, round(3.5) is 4 and round(-2.5) is -2. Over many values, about half of the ties go up and half go down, so a total of rounded numbers does not drift upwards the way it does when every .5 is rounded up. This rule is called round half to even: The rule round() follows for ties. A value exactly halfway between two whole numbers goes to the even one, so round(2.5) is 2 and round(3.5) is 4..
  • round(x, n) rounds to n decimal places, and a negative n rounds to tens, hundreds and so on: round(1234, -2) is 1200.
  • int(x) drops the fractional part, so it rounds towards zero: int(-3.99) is -3. Compare -7 // 2, which is -4, with int(-7 / 2), which is -3.

The math module adds two more directions: math.floor() always goes down, as // does, and math.ceil() always goes up. The table runs all four on the same values, ties first:

Four ways to make a whole number Python · whole_numbers.py
import math

print("    x  round  int  floor  ceil")
for x in [2.5, 3.5, -2.5, 3.99, -3.99]:  # ties first, then near-misses
    print(f"{x:5}  {round(x):5}  {int(x):3}  {math.floor(x):5}  {math.ceil(x):4}")

Output

    x  round  int  floor  ceil
  2.5      2    2      2     3
  3.5      4    3      3     4
 -2.5     -2   -2     -3    -2
 3.99      4    3      3     4
-3.99     -4   -3     -4    -3

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 whole_numbers.py

Read the int and floor columns: they agree on every positive value and part company on the rows for -2.5 and -3.99, because int() moves towards zero and math.floor() moves down. round() goes to the nearest whole number, with the tie 2.5 going to the even 2, and math.ceil() always moves up.

Choose by what the whole number is for

Use round() for the nearest value, int() to throw the fraction away, and math.ceil() when every part needs a place of its own: 23 search results at 10 a page need math.ceil(23 / 10), which is 3 pages.

Rounding a float to a number of decimal places, as in round(2.675, 2), holds one more surprise, which the next lesson explains.

Rounding Calculator Compare round-half-to-even with the other rounding modes on your own numbers.

Checkpoint

Check: Making a whole number from a float

  1. Question 1 of 2 What does round(4.5) return?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 4

    4.5 is exactly halfway between 4 and 5, and round() sends a tie to the even neighbour, which is 4. round(5.5) would give 6.

  2. Question 2 of 2 Which of these gives -3?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: int(-3.7)

    int() truncates towards zero, round() looks for the nearest whole number, and // and math.floor() go down. For -3.7 only int() gives -3; the other three give -4.

Practise: split a bill to the last paisa

Money counted in whole paise is a job for ints, //, % and divmod(). Write a function that splits a bill among friends so that the shares add up exactly and differ by one paisa at most, and run its sample tests in your browser; a first hint is ready when you want it:

Exercise · Easy · Python

Split a bill fairly, to the last paisa

Friends share a bill, and the app that splits it counts money in whole paise (100 paise make one rupee; the same code works for cents). Write split_amount(total_paise, people), which returns a list with one share per person:

  • the shares add up to exactly total_paise, so not a single paisa is lost or invented;
  • no two shares differ by more than 1 paisa;
  • the larger shares come first.

For example, split_amount(10000, 3) returns [3334, 3333, 3333], and split_amount(2, 5) returns [1, 1, 0, 0, 0]. When people is less than 1, or total_paise is negative, raise ValueError.

Use divmod(): its first result is what everyone pays, and its second says how many people pay one paisa more.

Starter code · split.py

def split_amount(total_paise, people):
    """Return one share per person, in paise: they add up to total_paise and differ by at most 1."""
    # Replace this line with your code.
    return []
The sample tests · test_split.py
from split import split_amount


def raises_value_error(total_paise, people):
    """True when split_amount(total_paise, people) raises ValueError."""
    try:
        split_amount(total_paise, people)
    except ValueError:
        return True
    return False


def test_even_split():
    """splits evenly when the total divides exactly"""
    assert split_amount(900, 3) == [300, 300, 300]


def test_extra_paise_first():
    """gives the paise that are left over to the first shares"""
    assert split_amount(10000, 3) == [3334, 3333, 3333]
    assert split_amount(10001, 3) == [3334, 3334, 3333]


def test_fair_and_complete():
    """always returns one share per person, adding up to the total, at most 1 paisa apart"""
    for total, people in [(10000, 3), (12345, 7), (1, 4), (999, 10), (250000, 6)]:
        shares = split_amount(total, people)
        assert len(shares) == people
        assert sum(shares) == total
        assert max(shares) - min(shares) <= 1


def test_one_person():
    """lets one person pay everything"""
    assert split_amount(4999, 1) == [4999]


def test_zero_total():
    """gives everyone 0 when the bill is 0"""
    assert split_amount(0, 4) == [0, 0, 0, 0]


def test_fewer_paise_than_people():
    """gives some people 0 when there are fewer paise than people"""
    assert split_amount(2, 5) == [1, 1, 0, 0, 0]


def test_bad_input():
    """raises ValueError for fewer than one person or a negative total"""
    assert raises_value_error(100, 0)
    assert raises_value_error(100, -2)
    assert raises_value_error(-5, 2)
A hint

divmod(10000, 3) is (3333, 1): everyone pays 3333 paise and one person pays one more. Lists can be built with operators too: [7] * 3 is [7, 7, 7], and + joins two lists, so [3334] * 1 + [3333] * 2 is the answer for this example. For the errors, raise ValueError("…") stops the function with that message.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then work through the lesson’s own questions. Each one is explained the moment you answer it, and the next one is chosen from the idea where your answers have been weakest so far:

Practice that adapts to you

Practise this lesson

16 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 16 What does this print?

    Read the code, then choose one answer.

    print(1_00_000 + 1)
    Show the answer: Question 1 of 16

    Answer: 100001

    Underscores between digits are ignored (PEP 515), so 1_00_000 is the int 100000, and the sum is 100001.

  2. Question 2 of 16 What does this print?

    Read the code, then choose one answer.

    x = 2e3
    print(x, type(x))
    Show the answer: Question 2 of 16

    Answer: 2000.0 <class 'float'>

    A decimal point or an e makes a float. 2e3 means 2 × 10³, the float 2000.0, which print() shows as 2000.0.

  3. Question 3 of 16 A program contains the line x = 08. What happens when you run it?

    Choose one answer.

    Show the answer: Question 3 of 16

    Answer: Python stops with a SyntaxError before running any line

    Leading zeros are not allowed in decimal int literals, so Python reports a SyntaxError, with a message that suggests 0o in case octal was meant. Keep values with leading zeros, such as PINs, as strings.

  4. Question 4 of 16 Which of these expressions give a float?

    Choose every answer that is right.

    Show the answer: Question 4 of 16

    Answer:

    • 7 // 2.0
    • 2 ** -1
    • 8 / 4

    / always gives a float (2.0 here), a negative power gives a float (0.5), and floor division of a float gives a float (3.0). 7 // 2 is the int 3, 2 ** 10 the int 1024, and int(7.9) the int 7.

  5. Question 5 of 16 What does this print?

    Read the code, then choose one answer.

    print(2 ** -1, 2 ** 3)
    Show the answer: Question 5 of 16

    Answer: 0.5 8

    ** gives an int for two ints unless the power is negative; 2 ** -1 is 1 / 2, the float 0.5.

  6. Question 6 of 16 marks = [70, 85, 90]. Which expression gives their average, 81.67 when rounded to two places?

    Choose one answer.

    Show the answer: Question 6 of 16

    Answer: sum(marks) / len(marks)

    An average needs the exact quotient, so use /. Use // only when you need a whole number, such as a position or a count of full boxes.

  7. Question 7 of 16 What is the value of -7 // 2?

    Type a number.

    Show the answer: Question 7 of 16

    Answer: -4

    -7 / 2 is -3.5, and floor division rounds down, towards minus infinity, so the result is -4. Dropping the fraction instead, as int(-7 / 2) does, gives -3.

  8. Question 8 of 16 What does this print?

    Read the code, then choose one answer.

    print(-7 % 3)
    Show the answer: Question 8 of 16

    Answer: 2

    -7 // 3 is -3 (rounded down from -2.33…), and -7 - 3 * -3 is 2. With a positive divisor the remainder is never negative: it has the sign of the number you divide by.

  9. Question 9 of 16 Which rule do // and % always satisfy for ints a and b, with b not 0?

    Choose one answer.

    Show the answer: Question 9 of 16

    Answer: a == b * (a // b) + a % b

    divmod(a, b) returns (a // b, a % b), and the two always rebuild a: b * (a // b) + a % b == a. The check column of floor_and_remainder.py prints that sum for every sign.

  10. Question 10 of 16 A 24-hour clock shows 3. Which hour was it 5 hours earlier, worked out as (3 - 5) % 24?

    Type a number.

    Show the answer: Question 10 of 16

    Answer: 22

    3 - 5 is -2, and -2 % 24 is 22, because -2 // 24 is -1 and -2 - 24 * (-1) is 22. Two hours before midnight is 22:00, with no special case for going back past 0.

  11. Question 11 of 16 x = 10 ** 5000 works, but str(x) raises a ValueError. Why?

    Choose one answer.

    Show the answer: Question 11 of 16

    Answer: CPython refuses to convert ints of more than 4,300 decimal digits to text unless you raise the limit, because such conversions are slow

    Ints have no size limit, so computing 10 ** 5000 is exact. Converting between int and decimal text is slow for huge numbers, which a program reading untrusted input could be attacked with, so CPython limits it to 4,300 digits by default. Hexadecimal is not limited, and sys.set_int_max_str_digits() changes the limit.

  12. Question 12 of 16 Which statement about Python's int is true?

    Choose one answer.

    Show the answer: Question 12 of 16

    Answer: It grows as needed, so +, -, * and // on ints are always exact

    An int can be as large as memory allows, and arithmetic on ints is exact. Only conversions to and from decimal text have a default limit, of 4,300 digits.

  13. Question 13 of 16 A program computes n = 3 ** 20_000, an int of 9,543 decimal digits, and must write it to a file without changing the limit. Which line works with the default settings?

    Choose one answer.

    Show the answer: Question 13 of 16

    Answer: f.write(hex(n))

    Every conversion of an int to decimal text, by str(), repr(), print() or an f-string, is limited to 4,300 digits by default. Hexadecimal, octal and binary are not, and int(text, 16) reads hexadecimal back without a limit.

  14. Question 14 of 16 What does rounding.py print?

    What does this program print? Choose one answer.

    print(round(2.5), round(3.5), round(-2.5))  # a tie goes to the even neighbour
    print(round(2.567, 2), round(1234, -2))  # to 2 decimal places; to the nearest hundred
    print(int(3.99), int(-3.99))  # int() drops the fraction
    print(-7 // 2, int(-7 / 2))  # floor division and dropping the fraction differ
    Show the answer: Question 14 of 16

    Answer: it prints

    2 4 -2
    2.57 1200
    3 -3
    -4 -3

    round() sends a tie to the even neighbour (2.5 → 2, 3.5 → 4, -2.5 → -2), and a negative number of places rounds to hundreds. int() drops the fraction, so int(-3.99) is -3, while -7 // 2 rounds down to -4.

  15. Question 15 of 16 What does this print?

    Read the code, then choose one answer.

    print(round(0.5), round(1.5), round(2.5))
    Show the answer: Question 15 of 16

    Answer: 0 2 2

    round() uses round half to even: 0.5 → 0, 1.5 → 2, 2.5 → 2. Over many ties, about as many go up as down, so totals of rounded values do not drift.

  16. Question 16 of 16 Search results are shown 10 to a page. Which expression gives the number of pages needed for any number of results n?

    Choose one answer.

    Show the answer: Question 16 of 16

    Answer: math.ceil(n / 10)

    A count of pages, boxes or buses has to round up whenever anything is left over, which is what math.ceil() does: math.ceil(23 / 10) is 3 and math.ceil(30 / 10) is 3.

Interview questions

Fresher · What is the difference between / and // in Python?

/ is true division: it always returns a float, even when the division is exact, so 10 / 2 is 5.0 and 17 / 5 is 3.4. // is floor division: it divides and rounds down, towards minus infinity, so 17 // 5 is 3 and -17 // 5 is -4, not -3. With two ints, // returns an int; if either operand is a float, it returns a float that holds a whole number, so 7 // 2.0 is 3.0. Its partner is %, the remainder that floor division leaves, and for ints the two always satisfy a == b * (a // b) + a % b. Use / when you want the exact quotient, such as an average, and // when you need a whole number, such as a list position or the number of full boxes.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A service is being ported from Java to Python. It puts events into one-minute buckets with offset / 60 and works out the second within the bucket with offset % 60, where offset is in seconds and can be negative. After the port, the numbers for events before the reference time differ. Explain why, and decide which behaviour each calculation needs.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    An API reads a JSON body and takes the quantity with int(body["quantity"]). A client sends a quantity of 50,000 digits. What happens in CPython 3.14, why does CPython behave that way, and how should the endpoint validate the field so that neither huge nor malformed values reach the business logic?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • int holds whole numbers of any size; float holds fractions in binary, with roughly 16 significant digits.
  • / always returns a float; // rounds down to a whole number and % gives the remainder; ** is the power operator, and ^ is not.
  • Floor division rounds towards minus infinity, so -7 // 2 == -4, and for ints a == b * (a // b) + a % b always holds; the remainder takes the sign of the divisor.
  • Mixing an int and a float gives a float; a list position must be an int.
  • CPython refuses int and string conversions longer than 4,300 decimal digits unless you raise the limit.
  • round() sends ties to the even neighbour, and int() rounds towards zero.

Terms in this lesson

floor division
Division that rounds down to a whole number, towards minus infinity, written //. 17 // 5 is 3, and -7 // 2 is -4.
literal
A value written straight into the code, such as 42, 3.5, 0xFF or "text". How a number literal is written decides its type; a decimal point or an e makes a float.
modulo
The remainder that floor division leaves, written %. 17 % 5 is 2; in Python the remainder takes the sign of the divisor, so -7 % 3 is 2.
round half to even
The rule round() follows for ties. A value exactly halfway between two whole numbers goes to the even one, so round(2.5) is 2 and round(3.5) is 4.
truncation
Rounding towards zero by dropping the fractional part, as int() does. int(-3.99) is -3; Java's integer division truncates too.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.