Corrected if else in loop