tuples (slides)

CSc 110 - tuples

Variable length parameter

Sometimes you want to handle a variable number of parameters (like print does)

print(1, 2, 3, 4, 5)
1 2 3 4 5

Variable length parameter

Add a * before your parameter name so that it accepts a variable number of arguments, gathering them into a tuple

def func(*values):
  print(values)
  for v in values:
    print(v)
  
def main():
  func(0, 2, 'quick', 4, 'brown', 'fox')
  
main()
(0, 2, 'quick', 4, 'brown', 'fox')
0
2
quick
4
brown
fox

Variable length parameter

Add a * before your parameter name so that it accepts a variable number of arguments, gathering them into a tuple

def concatenate(*values):
  new_string = ""
  for v in values:
    new_string += str(v) + " "
  return new_string[:-1]

def main():
  print( concatenate("The", "temperature", "is", 82, "degrees"))
  
main()
The temperature is 82 degrees

Write a function

  1. Its name is min_max
  2. It takes a variable number of arguments: *values
  3. It returns the highest and lowest values in values

Name your file min_max_tuple.py, submit to Gradescope.

assert min_max(1) == (1, 1)
assert min_max(3,1) == (1, 3)
assert min_max(2,4,6) == (2, 6)
assert min_max() == (None, None)

Write a function – solution

def min_max(*values):
  max = None
  min = None
  for v in values:
    if max == None or v > max:
      max = v
    if min == None or v < min:
      min = v
  return min, max

def main():
  assert min_max(1) == (1, 1)
  assert min_max(3,1) == (1, 3)
  assert min_max(2,4,6) == (2, 6)
  assert min_max() == (None, None)
  print("Passed all tests")
  
main()
Passed all tests