Comets are probably ejected from the Oort Cloud or Kuiper Belt as a result of a collision.
Once disturbed, they are caught by the Sun’s gravity and fly into an orbit around the star.
Comets that orbit the Sun once every 200 years, or less, are called short-period comets, and probably come from the Kuiper Belt or the Oort Cloud.
Comets that take longer than 200 years are called long-period comets, and probably come from the Oort Cloud.
Some comets do not have a periodic orbit at all, but swing around the Sun only to go flying off into space forever.