LehreWiki

Variable names

Allowed names for identifier (name of variable or function):

Name space

The Python interpreter maps the name of an identifier in the active name space. The active name space depends on the active code block (module, function). The identifier can be local or global with respect to the active code block.

   1 def func(a):
   2     a=a+1 # a is visibly only within func()
   3     print a
   4 
   5 b=func(1)
   6 print b
   7 print a # This will throw a NameError exception

   1 import scipy
   2 scipy.pi # pi is in the name space of scipy
   3 
   4 from scipy import pi
   5 pi # pi is in the active name space
   6 
   7 from scipy import *
   8 pi # all identifiers of scipy are in the active name space
   9 
  10 del(pi) # Deletes pi from the active name space
  11 reset   # ipython function to delete all identifiers

Built-in datatypes

Scalar

Casting

Sequences

String

   1 s1='Hello world'
   2 s2="Hello world"
   3 s1==s2
   4 
   5 s='"'
   6 s="'"

Dictionary

   1 D={1:'one',2:'two','one':1,'two':2}
   2 D['one']
   3 D[1]

Extended data types

Array

NumPy/SciPy provides a multidimensional array data type. An array can hold arbitrary Python objects but usually they are used for N-dimensional numeric data types.

Array creation

Array indexing

Functions

Function with one argument

In [124]: def quadrat(x):
   .....:     return x**2
   .....:

In [125]: quadrat(2)
Out[125]: 4

Function with variable number of arguments

In [126]: def printargs(*args):
   .....:     for arg in args:
   .....:         print arg
   .....:

In [127]: printargs(a)
[1, 2, 3]

In [128]: printargs(a,range(4))
[1, 2, 3]
[0, 1, 2, 3]

Function with variable number of keywords

In [131]: def printkeys(**kw):
   .....:     for k in kw.keys():
   .....:         print k,kw[k]
   .....:

In [132]: printkeys(key1=10,key2='Hallo')
key2 Hallo
key1 10

Function with functions as arguments (expert)

Functions can be passed to functions as arguments.

   1 from scipy import sin,pi
   2 
   3 def func(x,f):
   4         return f(x)
   5 
   6 print func(pi/2,sin)

eval(), apply()

In Matlab or IDL the passing of functions to functions works only with a detour using feval() or Call_function()

Of course, this way is possible in Python as well using the eval() or apply() function.

   1 apply(sin,(pi/2,))
   2 
   3 f='sin'
   4 x=pi/2.0
   5 eval(f+'('+str(x)+')')

In Fortran it is also possible to pass functions as arguments but with quite some overhead:

Lambda expressions (expert)

Lambda expressions are (anonymous) one line functions

   1 l=lambda x: x**2-1
   2 l(4)

Mapping (expert)

Similar as apply() works with one argument one can call map() with a sequence

   1 map(len,['Always','look','on','the','bright','side','of','life'])
   2 [6, 4, 2, 3, 6, 4, 2, 4]

The following example shows the combined usage of a lambda expression

   1 map(lambda s:len(s)+1,['Always','look','on','the','bright','side','of','life'])
   2 [7, 5, 3, 4, 7, 5, 3, 5]

Variable Scope (expert)

The scope of an identifier refers to the variable visibility. Variables inside a function have a local scope. Global variables can be declared and used but you should be very careful.

   1 def bad_style(x):
   2         # Name space of bad_style
   3         global y
   4         y=x 
   5         z=x
   6         return x
   7 
   8 # Name space of __main__
   9 x,y,z=2,2,2
  10 x=bad_style(1)
  11 print 'x=',x,'y=',y,'z=',z
  12 # y is changed!

A shell inside the shell (expert)

For debugging purposes it is sometimes useful to investigate local variables at some points. The following example demonstrates a feature of ipython:

   1 from IPython.Shell import IPShellEmbed
   2 ips=IPShellEmbed()
   3 
   4 def spam(a):
   5     b=a+' Spam!'
   6     ips()
   7     print b

In [1]: from spam import spam
In [2]: whos
Interactive namespace is empty.
In [3]: spam('Hello')

# Now we are in the ips() call

In [1]: whos
Variable   Type    Data/Info
----------------------------
a          str     Hello
b          str     Hello Spam!

In [2]: exit()
Do you really want to exit ([y]/n)? y
Hello Spam!

# We are now again in top level
In [4]: whos
Interactive namespace is empty.

LehreWiki: Python/Lesson2 (last edited 2008-11-03 13:36:26 by anonymous)