Flowers use petals to help them attract pollinators such as bees, insects, birds and bats. These pollinators collect nectar, a sweet source of food, from the flowers. While collecting nectar, the pollinator gets pollen on its body from the male parts of the flower. The pollinator then flies to another plant and spreads the pollen to the female parts of that flower.
To create a seed, the pollen from one flower must land on the stamen of another. Once the pollen lands on the stamen, it travels to the flower's ovaries where it fertilizes the egg. Fertilized eggs become seeds, and the ovary around the egg becomes a fruit.
Most flowers contain both male and female parts, but they have mechanisms that help prevent the pollen from fertilizing the egg in the same flower. This allows the plant to better ensure the genetic diversity of the next generation.
Not all plants work this way, however. Some plants do not use pollinators to spread their pollen but instead take advantage of the wind to move pollen from one flower to another. Some trees also have separate flowers that are either male or female.