find the nth hexagonal number in python

To find the nth hexagonal number in Python, we need to use the formula for the nth term of a hexagonal number sequence, which is:

main.py
Hexagonal(n) = n*(2n-1)
24 chars
2 lines

We can implement this formula in Python as follows:

main.py
def hexagonal_number(n):
    return n*(2*n - 1)
48 chars
3 lines

Here, the input n represents the nth term of the hexagonal number sequence, and the output is the corresponding hexagonal number.

We can test this function for different values of n to find the corresponding hexagonal numbers. For example, to find the 5th hexagonal number, we can call the function as follows:

main.py
hexagonal_number(5)
20 chars
2 lines

This will output 61, which is the 5th hexagonal number.

gistlibby LogSnag