Moved if statements inside the "for" operator

I figured out that the if statements could not be outside the for
statement. Also, needed to execute the commands in the right order.