9 Loops

  • R and Python include if and for as looping operator
  • Note indenting is important in Python; R is flexible although indented code is easier to read

9.1 R: if loop

x = 20

if (x %% 2 == 0){
    cat('The number ', x, ' is EVEN')
} else {
    cat('The number ', x, ' is ODD')
}

The number 20 is EVEN

9.2 Python: if loop


x = 20

if x % 2 == 0:
  print('The number ', x, ' is EVEN')
else:
  print('The number ', x, ' is ODD')

The number 20 is EVEN

9.3 R: for loop

x = 1:5

for (i in seq_along(x)){
    cat('\nThe square of the number ', i, ' is: ', i**2, ';')
}

The square of the number 1 is: 1 ; The square of the number 2 is: 4 ; The square of the number 3 is: 9 ; The square of the number 4 is: 16 ; The square of the number 5 is: 25 ;

9.4 Python: for loop


x = [1, 2, 3, 4, 5]

for i in x:
  print('The square of the number ', i, ' is : ', i**2, ';')

The square of the number 1 is : 1 ; The square of the number 2 is : 4 ; The square of the number 3 is : 9 ; The square of the number 4 is : 16 ; The square of the number 5 is : 25 ;