All labs · lesson 3 of 9

R vs Pythonbeginner15 min

R/Python Comparison: Functions

Master function creation and usage 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.

Functions are essential building blocks in programming. Let’s see how to create and use them in both languages.

Basic Function Definition

Here’s how to define a simple function in both languages.

Exercise 1

Create a function to square a number

# Define a function in Python
def square(x):
    return x * x

# Call the function
result = square(5)
print(f"5 squared is {result}")
print(f"10 squared is {square(10)}")
# Define a function in R
square = function(x) {
    return(x * x)
}

# Call the function
result = square(5)
print(paste("5 squared is", result))
print(paste("10 squared is", square(10)))

Functions Without Arguments

Functions don’t always need input parameters.

Exercise 2

Create a function that prints a greeting

# Function without arguments
def greet():
    print("Hello from Chatomics!")
    print("Happy coding!")

# Call it
greet()
# Function without arguments
greet = function() {
    print("Hello from Chatomics!")
    print("Happy coding!")
}

# Call it
greet()

Functions with Default Arguments

Default arguments make functions more flexible.

Exercise 3

Create a function with default parameters

from math import log

# Function with default argument
def log_fun(x, base=2):
    return log(x, base)

# Different ways to call
print(f"log2(8) = {log_fun(8)}")
print(f"log2(8) = {log_fun(8, 2)}")
print(f"log10(100) = {log_fun(100, 10)}")
# Function with default argument
log_fun = function(x, base=2) {
    return(log(x, base))
}

# Different ways to call
print(paste("log2(8) =", log_fun(8)))
print(paste("log2(8) =", log_fun(8, 2)))
print(paste("log10(100) =", log_fun(100, 10)))

Functions with Multiple Return Values

Sometimes you need to return multiple values.

Exercise 4

Return multiple values from a function

# Return multiple values using tuple
def calculate_stats(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return total, count, average

# Use the function
nums = [10, 20, 30, 40, 50]
total, count, avg = calculate_stats(nums)

print(f"Total: {total}")
print(f"Count: {count}")
print(f"Average: {avg}")
# Return multiple values using list
calculate_stats = function(numbers) {
    total = sum(numbers)
    count = length(numbers)
    average = total / count
    return(list(total=total, count=count, average=average))
}

# Use the function
nums = c(10, 20, 30, 40, 50)
result = calculate_stats(nums)

print(paste("Total:", result$total))
print(paste("Count:", result$count))
print(paste("Average:", result$average))

Key Differences

  • Python uses def keyword and requires indentation for function body
  • R uses function() keyword and curly braces {} for function body
  • Python return is a keyword, R return() is a function (but optional)
  • Python returns multiple values as tuples, R typically uses lists
  • Python requires strict indentation, R uses curly braces