find the nth nonagonal number in python

The n-th nonagonal number can be computed as n*(7*n-5)//2. Here's a function that takes the value of n as an argument and returns the corresponding nonagonal number:

main.py
def nonagonal_number(n):
    return n*(7*n-5)//2
49 chars
3 lines

Here, // is used for integer division, which ensures that the result is always an integer even if n produces a non-integer result.

You can use this function to find the 10th nonagonal number as follows:

main.py
>>> nonagonal_number(10)
145
29 chars
3 lines

This means that the 10th nonagonal number is 145.

gistlibby LogSnag