Programming in Python

BEES 2021

Agenda

  • Tuples
  • Debuging

tuples

  • An ordered sequence of elements, can mix element types
  • Cannot change element values, "immutable"
  • Represented with parentheses
# A tuple
x = ("Paris Hilton", 1981)
type(x)

# You can address the members of a tuple using indices
x[0]

# A tuple of length one is specified like this
x = (1,)

# Note x is not a tuple here, as the interpretor just simplifies out the brackets
x = (1)

# Slicing works just like with strings:
x = ("a", "sequence", "of", "strings")
x[1:] 

tuples

  • Conveniently used to swap variable values

 

 

 

  • Used to return more than one value from a function
def quotient_and_remainder (x, y):
    q = x // y
    r = x % y
    return (q, r)

(quot, rem) = quotient_and_remainder (4, 5)

tuples

  • Immutable

 

 

 

 

  • Length

 

 

  • In operator

 

 

 

julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
len(julia) # The length of the tuple
x = ("a", "sequence", "of", "strings")
x[0] = "the" # Error

# To make edited tuples from existing tuples you therefore slice and dice them

print(("the",) + x[1:])
# Like strings we can do search in tuples using the in operator:
5 in (1, 2, 3, 4, 5, 6)
5 not in (1, 2, 3, 4, 5, 6)

Tuple assignment

Multiple return values

Nested/composed tuples

tuple comparison

Debugging revisited

  • Syntax Error
  • Runtime Error
  • Semantic/Logical Error

Syntax error Example

runtime/semantic error

debug Example

Questions?