PSPP Python

Page content

Python

For Loops

really comfortable with range function:

for n in range(2,10):
  for x in range(2, n):
    if n% x == 0:
      print(n, 'equals', x, '*', n//x)
      break
  else:
    #Loop fell through without finding a factor
    print(n, 'is a prime number')

Scope Rules

  • different Scopes
    • local

      inside function(method,…)

    • global

      in the surrounding modul

    • built-in

      pre defined names(open, len,…)

  • function call creates a local scope
  • search order when reading

    local > global > built-in

function return value

def funktion():
    return 1, 2, 3
eins, zwei, drei = funktion()
print(drei)
# 3
print(funktion())
# (1, 2, 3)

Lambdas

Lambdas are anonymous functions

lmbd = lambda(x : 2 * x)
#use it with map
test_list = [1,2,3,4,5,6]
doubled = map(lmbd,test_list)
print(list(doubled))