Iteration Worksheet

Back to Week 5 Notes

Problem 1

Write a python function print_seq that accepts one integer argument prints out, one number on each line, sequential positive integers less than or equal to the argument.

def print_seq(x):
  # your code here
print_seq(7)
1
2
3
4
5
6
7

Problem 2

Write a python function print_even_seq that accepts one integer argument prints out, one number on each line, sequential even positive integers less than or equal to the argument.

# define the function here
print_even_seq(11)
2
4
6
8
10

Problem 3

Write a function sum_evens_less that takes an integer argument, finds the even numbers less than or equal to the argument, and returns the sum of these even numbers.

  • sum_evens_less(5) finds 2 and 4, and returns the sum 6
  • sum_evens_less(8) finds 2, 4, 6, and 8, and returns the sum 20
# define the function here
assert sum_evens_less(5) == 6
assert sum_evens_less(6) == 12
assert sum_evens_less(10) == 30

Problem 4

Write a function check_prime that accepts an integer argument \(\geq 2\) and returns a bool: True if the argument is prime, False if it is not.

  • check_prime(3) returns True
  • check_prime(4) returns False
  • check_prime(13) returns True
  • check_prime(24) returns False
def check_prime(zed):
  return
assert check_prime(3) == True
assert check_prime(12) == False
assert check_prime(13) == True
assert check_prime(24) == False

Problem 5

Write a function largest_square that takes one argument, an integer, and returns the largest perfect square that is less than that integer:

  • largest_square(10) returns 9 (3 squared)
  • largest_square(25) returns 16 (4 squared)
  • largest_square(26) returns 25 (5 squared)
def largest_square( ): # add an argument
  # define the function

assert largest_square(5) == 4
assert largest_square(12) == 9
assert largest_square(101) == 100
assert largest_square(81) == 64

Problem 6

Write a function sum_next_three that takes an argument (a positive int or float), finds the three next largest multiples of three that are greater than or equal to the argument, and returns their sum:

  • sum_next_three(4.5) finds 6, 9, and 12: the sum is \(6 + 9 + 12 = 27\), so 27 is returned
  • sum_next_three(3) finds 3, 6, and 9: the sum is \(3 + 6 + 9 = 18\), so 18 is returned

# define the function here
assert sum_next_three(4) == 27
assert sum_next_three(6.2) == 36
assert sum_next_three(18) == 63
assert sum_next_three(1) == 18

Back to Week 5 Notes