-
For Loops [R,Python]
for loops are dedicated to iterate though a specific number of things. Those things can be lists, vectors, etc. We can either set a specific number of iterations or have a loop go though a set list of something and perform a set operations on each element of the list. For example, we can go through a list of values and perform a specific operation such as adding/subtracting/dividing etc. or capitalizing each of the elements. Let’s see how thing can be done with R and Python:
[R] values <- c(1,2,3,4,5) # Let's create a for loop for (i in values){ print(i + 1) } [output] [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 # The output of the above for loop is a value with an added 1 to it.[Python] values = [1,2,3,4,5] # Let's create a for loop for i in values: print(i + 1) [output] 2 3 4 5 6 -
While Loops [R,Python]
In programming, loops allow us to perform repetitive actions without having to write repetitive code. Here are a few examples:
[R] # Let's declare and initialize a variable temp temp <- 75 # Let's write a loop while (temp > 65) { print(paste("The temperature is:",temp)) if (temp > 80) { print("Too hot!") temp <- temp - 20 print(paste("Temperature has been reset to:",temp)) } else { print("Still too warm!") temp <- temp - 10 print(paste("Temperature has been reset to:",temp)) } } [output] [1] "The temperature is: 75" [1] "Still too warm!" [1] "Temperature has been reset to: 65"[Python] # Let's declare and initialize a variable temp temp = 75 #Now, let's create a loop while (temp > 65): print(f'The temperature is: {temp}') if (temp > 80): print("Too hot!") temp -= 20 print(f'Temperature has been reset to {temp}') else: print("Still too warm!") temp -= 10 print(f'Temperature has been reset to {temp}') [output] The temperature is: 75 Still too warm! Temperature has been reset to 65
