Sunday, March 26, 2017

Python Part4: For loop, argument passing and Tuple

For loop

  • items = [a, b, c, d] 
  • for item in items: 
    •  print(item) 
  •  for i in range(5) 
    •  print(i)

Argument passing

  • Function with arguments.
  • def modify(k) 
    •  k.append(13) 
    •  print(k) 
  • m = [6, 7, 8, 9] 
  • modify(m) 
  • Default arguments.
  • def DisplayMessage(m='nothing') 
    • print(m) 
  • message = 'Welcome to python' 
  • DisplayMessage(Message) 
  • DisplayMessage()

Tuple

  • Heterogeneous immutable collection. 
  • Delimited by parentheses.
    • For example t = ("norway", 4.953, 3) 
  • Items separated by commas.
  • Element access with square brackets and zero-based index. T[index] 
    • >>> t[0] 
    • 'Norway'
  • len(t) for number of elements. 
    • >>> len(t) 
    • 3
  • Iteration with for loop. 
    • for item in t: 
    • print(item) 
      • Norway 
      • 4.953 
  • Concatenation with + operator. 
    • t + (338186.0, 2659) 
    • ('Norway', 4.953, 3, 338186.0, 2659) 
  • Reputation with * operator. 
    • t * 3 
    • ('Norway', 4.953, 3, 'Norway', 4.953, 3, 'Norway', 4.953, 3)
  • Tuple can contain any kind of object. 
  • Nested tuples.
    • A = ((245, 446), (90, 456)) 
  • Chain square-brackets indexing to access inner elements. 
    • A[1][0] 
    • 90 
  • Can’t use one object in parentheses as a single element tuple. 
  • For a single element tuple include a trailing comma. 
    • K = (234, ) 
  • The empty tuple is simply empty parentheses. 
    • E = ()
  • Delimiting parentheses are optional for one or more elements.
    • p = 1, 1, 1, 4, 6, 19 
    • >>> p 
    • (1, 1, 1, 4, 6, 19) 
  • Tuples are useful for multiple return values. 
    • def MinMax(items) 
      • Return Min(items), Max(items) 
    • >>> MinMax([33, 30, 9, 82, 87]) 
    • (9, 87)
  • Tuple unpacking allow us to destructure directly into named references. 
    • lower, upper = MinMax([33, 30, 9, 82, 87]) 
    • >>> lower 
    • >>> upper 
    • 87
  • Tuple unpacking works with arbitrarily nested tuples (although not with other data structure) 
    • (a, (b, (c, d))) = (4, (3, (2, 1))) 
    • >>> a 
    • >>> b 
    • >>> c 
    • >>> d
    •  1 
  • a, b = b, a is the idiomatic python swap.
  • Use the tuple constructor to create tuples from other iterable series of objects. 
    • >>> tuple([234, 444, 897]) 
    • (234, 444, 897) 
    • >>> tuple("car") 
    • ('c', 'a', 'r') 
  • The in and not in operators can be used with tuples - and other collection types – for membership testing. 
    • >>> 5 in (3, 5, 9, 13) 
    • True 
    • >>> 5 not in (3, 5, 9, 13) 
    • False

No comments:

Post a Comment