Valency is the number of electrons an atom uses to form bonds.
Atoms gain, lose or share valence electrons to achieve stable noble gas electronic configuration. Valence electrons are the electrons present in the outermost shell of an atom.
Hydrogen has 1 shell and 1 electron. It needs one more electron to achieve stable noble gas electronic configuration. (Remember, first shell can only hold 2 electrons.) Hydrogen uses 1 electron to form a bond, hence its valency is 1.
Magnesium has 12 electrons (2,8,2). It is easier to lose 2 electrons than to take in 6 electrons to achieve stable octet configuration. It loses its 2 valence electrons to form ionic bond, hence its valency of Mg is 2.
Carbon uses all its 4 valence electrons to form bonds, hence it has a valency of 4.
Oxygen has 8 electrons (2,6). It has 6 valence electrons, however it only uses 2 of its outermost electrons in bonding to achieve stable noble gas electronic configuration. Hence, valency of oxygen is 2.
Valency of other common atoms are shown in the image.
All elements in group 0 of the periodic table have a valency of 0. They have attained stable noble gas electronic configuration. Hence, they do not gain, lose or share electrons. They are chemically inert.