Pre work

Make sure that you are comfortable with git and have a basic understanding of R and Python. If you need a refresher, please see the Precept 1 materials and external resources. Feel free to ask any remaining questions.

Before coming to precept, you should have:

Precept 2 – Introduction to Control Flow in R

Control flows in R determine the sequence in which the instructions are executed. This ability to control the flow of execution allows for more complex and flexible scripts.

Basic conditionals

In R, the basic conditional statements are if, else, and else if.

set.seed(42) # This ensures that the random number generator will produce the same results each time the script is run
x <- runif(1, 0, 10)

if (x > 5) {
     print("x is greater than 5")

} else if (x < 5) {
     print("x is less than 5")

} else {
     print("x is equal to 5")
}
## [1] "x is greater than 5"

Loops

There are two primary loops in R - for and while. for loops are used when the number of iterations is known, while while loops are used when the number of iterations is unknown and require an iterator variable.

For loop

for (i in 1:5) {
     print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

While loop

counter <- 1 # this is the iterator variable

while (counter <= 5) {
     print(counter)
     counter <- counter + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

Functions

Functions are blocks of reusable code. Functions are used to perform a specific task and are only run when they are called.

calculate_sum <- function(a, b) { # a and b are the function arguments
     return(a + b)
}

calculate_sum(3, 4) # this is where we call the function
## [1] 7

Scoping

Scoping refers to the visibility of variables. In R, there are two main scopes: global and local. Global variables are accessible throughout the entire script, while local variables are only available within the function or script in which they are defined.

global_var <- 10

function_with_scope <- function() { 
  local_var <- 5
  return(global_var + local_var) # function_with_scope() has access to global_var even though it is not defined in the function
}

function_with_scope()
## [1] 15

Recursion

A function that calls itself is known as a recursive function. Recursive function are only used for very specific problems, such as when you need to solve a problem that can be broken down into smaller, similar problems.

factorial <- function(n) {
     if (n <= 1) {
          return(1)

     } else {
     return(n * factorial(n-1)) # this is where factorial() calls itself
     }
}

factorial(5)
## [1] 120

Precept 2 – Introduction to Control Flow in Python

This Python lesson will cover the same control flow basic as were demonstrated in R. These sections will be similar to those in R, with slight differences in syntax. Don’t forget that R and Python are indexed differently (1 vs 0, respectively)!

Basic conditionals

In Python, the basic conditional statements are if, else, and elif. Here, the indentation is important for determining which code belongs to which conditional statement.

import numpy as np

np.random.seed(10) # the random number generator will produce the same seed (seed #10) each time the script is run
x = np.random.uniform(size = 1, low = 5, high = 10)

if x > 5:
     print("x is greater than 5")

elif x < 5:
     print("x is less than 5")

else: 
     print("x is equal to 5")
## x is greater than 5

Loops

There are two primary loops in Python - for and while.

For loop

for i in range(1,6):
     print(i)
## 1
## 2
## 3
## 4
## 5

While loop

counter = 1 # this is the iterator variable

while counter <= 5:
     print(counter)
     counter += 1 # the += operator is shorthand for counter = counter + 1
## 1
## 2
## 3
## 4
## 5

Functions

Functions are blocks of reusable code.

def calculate_sum(a, b): # a and b are the function arguments
     return a + b

calculate_sum(3, 4) # this is where we call the function
## 7

Scoping

Scoping refers to the visibility of variables.

global_var = 10

def function_with_scope():
     local_var = 5
     return global_var + local_var # function_with_scope() has access to global_var even though it is not defined in the function

function_with_scope()
## 15

Recursion

A function that calls itself is known as a recursive function.

def factorial(n):

     if n <= 1:
          return 1

     else:
          return n * factorial(n-1) # this is where factorial() calls itself

factorial(5)
## 120

Submission

For this precept, please submit a single R file OR Python file containing the answers to the exercises found here. Please make intermediate commits in your development branch as you write to get in the habit of committing often. You should commit at least once for each question. Finally, you should submit a pull request and merge your development branch into your main branch. As a reminder, once you merge this PR, your assignment will be marked as complete and may be graded.

Exercises

1. Conditionals

Consider a vector (R) or list (Python) containing the values: 85, 77, 90, 65, 89, 72, 91, 68, 80.

Write a conditional script that:

  1. Tags grades above 90 as “Excellent”
  2. Between 80 and 90 (inclusive) as “Good”
  3. Below 80 as “Fair”

Store the result in a new variable called grade_tags. Ensure the order in grade_tags corresponds to the order of grades in the grades vector, and print the result.

2. For

Create a sequence of numbers from 3 to 15 (included). Using a for loop, compute the cumulative product of these numbers and print the results.

3. While

Starting with a number 50, decrease it by 5% in every iteration using a while loop. Continue the iterations until the number goes below 20. Return and print the number of iterations it took.

4. Functions with conditionals and loops

Write a function named series_sum that accepts two arguments: a start value ‘s’ and an end value ‘e’. The function should sum all numbers from ‘s’ to ‘e’. However, if a number in the series is divisible by 3, it should be skipped.

Tip: The modulo operator (%% in R and % in Python) returns the remainder of the division of two numbers.

# as in R
5%%2
## [1] 1
# as in Python
5%2
## 1

5. Recursive Functions

The Lucas series is a sequence of numbers similar to the Fibonacci series but starts with 2 and 1 instead of 0 and 1. Write a recursive function lucas that computes the nth value of the Lucas series.