All labs · lesson 4 of 9

R vs Pythonbeginner18 min

R/Python Comparison: Control Flows

Learn if/else statements and loops in both R and Python

Edit any code block and press Run (or Ctrl/⌘ + Enter, or Shift + Enter). The code runs in your browser, so there is nothing to install. The first run downloads the language once; later runs are instant.

Control flow statements let you make decisions and repeat actions in your code.

If/Else Statements

Conditional logic is fundamental to programming.

Exercise 1

Create a function using if/else

# Absolute value function
def absolute(x):
    if x >= 0:
        return x
    else:
        return -x

print(f"absolute(5) = {absolute(5)}")
print(f"absolute(-5) = {absolute(-5)}")
print(f"absolute(0) = {absolute(0)}")
# Absolute value function
absolute = function(x) {
    if (x >= 0) {
        return(x)
    } else {
        return(-x)
    }
}

print(paste("absolute(5) =", absolute(5)))
print(paste("absolute(-5) =", absolute(-5)))
print(paste("absolute(0) =", absolute(0)))

Elif/Else If Chains

Handle multiple conditions with elif/else if.

Exercise 2

Classify a number as positive, negative, or zero

# Multiple conditions
def classify_number(x):
    if x > 0:
        return "positive"
    elif x < 0:
        return "negative"
    else:
        return "zero"

print(f"10 is {classify_number(10)}")
print(f"-5 is {classify_number(-5)}")
print(f"0 is {classify_number(0)}")
# Multiple conditions
classify_number = function(x) {
    if (x > 0) {
        return("positive")
    } else if (x < 0) {
        return("negative")
    } else {
        return("zero")
    }
}

print(paste("10 is", classify_number(10)))
print(paste("-5 is", classify_number(-5)))
print(paste("0 is", classify_number(0)))

For Loops

Repeat actions with for loops.

Exercise 3

Iterate through numbers and calculate squares

# For loop in Python
print("Squares of numbers 1-5:")
for i in range(1, 6):
    square = i ** 2
    print(f"{i} squared = {square}")

# Loop through a list
fruits = ['apple', 'banana', 'cherry']
print("\nFruits:")
for fruit in fruits:
    print(f"I like {fruit}")
# For loop in R
print("Squares of numbers 1-5:")
for (i in 1:5) {
    square = i ^ 2
    print(paste(i, "squared =", square))
}

# Loop through a vector
fruits = c('apple', 'banana', 'cherry')
print("Fruits:")
for (fruit in fruits) {
    print(paste("I like", fruit))
}

While Loops

Repeat until a condition is false.

Exercise 4

Use a while loop to count down

# While loop
count = 5
print("Countdown:")
while count > 0:
    print(count)
    count -= 1
print("Blast off!")
# While loop
count = 5
print("Countdown:")
while (count > 0) {
    print(count)
    count = count - 1
}
print("Blast off!")

Key Differences

  • Python uses elif, R uses else if
  • Python requires indentation, R uses curly braces {}
  • Python uses range(start, stop) for numeric loops
  • R uses start:stop for sequences
  • Python has for item in collection:, R has for (item in collection)
  • Conditions in R should be in parentheses: if (condition), Python doesn’t require them