It was inventented in the XVI century in Italy (which at the time was not yet united).
There are some records about first lottery-like events being held in Florence in 1528.
Time-recurring lottery was invented in the Republic of Genoa around 1576, in order to regulate pre-existing gambling over the election of the Doge (governor of the republic, elected every two years by and among the aristocracy).
Modern lottery (with numbers drawing and such) was then formulated and regulated in 1620, still in Genoa.
Regarding the purpose, it is a regulation over pre-existing underground gambling practices, in order for the state to collect money via taxes and lottery events organization.
Source: Alan Wykes, "Gambling" - and several other historical records on Republic of Genova, and Lotto (Italian nationwide lottery, pre-dating the country unification).