Answer: Count only the electrons in the highest shell s and p orbitals when determining valence.
Explanation: I'm glad you asked this question. It is often not well explained. The term valence electrons is assigned to only the electrons in an element's highest energy level. These reside only in the s and p orbitals, and not the d or f, as I'll explain later. The s orbital can hold 2 electrons and the p can hold 6. Potassium, K, has an s orbital in its highest energy shell, 4. It contains only 1 electron, so it has a valency of 1.
Calcium, Ca, has 2 in its highest energy level: 4s^2, so it has a valency of 2. Moving to the right, the element scandium, Sc, add another electron, but it goes into the 3d orbital. 3d is in the 3rd energy shell, so it is not counted as a valence electron. Only after we move further right, to gallium, Ga, do we start adding electrons to the 4th energy level again - the 4p orbitals can accept up to 6 electrons. Ga has 3 valence electrons - 2 in the 4s and 1 in the 4p. Oxygen has 2 in the 2s and 4 in the 4p orbitals, for a total of 6. It is close to having a comple outer shell (2 in the 2s and 6 in the 2p). Just 2 more electrons would fill both the 2s and 2p orbitals for a total of 8 valence electrons, a stable configuration (the same configuration as thje stable gas Neon).