There are a number of Python keywords that cannot be used as variable names. These keywords are:
and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield
Note: Be aware of the keyword lambda
, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.
print('This is old %s %10.3f %d' % ('type',3.0,1))
x=1
print (type(x))
x=1.0
print (type(x))
x=True
print (type(x))
x=1.0+1.j
print (type(x))
x = 'my string'
print (type(x), len(x))
x = [1,2,3.0,2.+3j]
y = (1,2,3.0,2.+3j)
print(type(x))
print(type(y))
[type(i) for i in x], [type(i) for i in y]
print(1.0, 'str1', 'str2', 'str3'+' str4')
Python2 type of printing, still very useful
from math import *
print( 'value of pi is %6.4f and integer part %d' % (pi, int(pi)) )
More Python3 oriented printing
print('value of pi is {0:6.4f} and integer part {1:d}'.format(pi,int(pi)))
We can also skip default values, like position argument or types
print('value of pi is {:6.4f} and integer part {:}'.format(pi,int(pi)))
The syntax for creating list is [..,..,]
The index starts with 0, like in C (not like in Fortran). Negative indices allowed.
List can contain different types, and can be nested
Slicing works just as with strings or arrays. Notation [start:end:step], defaults can be omitted
l1=[1,'a',1.0,-1.1]
print(l[0], l[-1])
l2=[1,[1,[2,3]]] # nested list
print(l1[1::2] ) # start with 1st, and take every second till the end
print(list(range(10))) # range used in loops
print(list(range(1,10,2))) # similar sintax: start,end,step
Modifying a list:
l=[] # empty list
l.append('A') # add at the end
l.append('d')
l.append('f')
print(l)
l[1]='e' # modify
print(l)
l.insert(1,'k') # insert at specific location to extent the list
print(l)
l.remove('f') # remove specific element, which must exist
print(l)
del l[1] # remove an element at specific location
print(l)
Are like lists, except non-modifiable.
Most important use in returning from a function, and use in print statement.
point=(10,20)
# point[0]=1 can not be done
point=(1,20) # modifying the entire tuple is allowed, i.e., it is not a constant
#unpack it
x,y = point
print(x,y)
print('I want nice printout %10.3f' % (pi,))
def Simple():
# need to return several things
return ('a','b','c')
print(Simple())
Dictionaries are like lists, but their keys are not integers, rather key can be any scalar type or tuple of scalar types
Dictionary is constructed by {...}
# This acts just like list
di={}
di[0]='a'
di[1]='b'
di[2]='c'
print(di)
# Generic keys
dj={}
dj[300]='c'
dj[600]='d'
dj['cde']=1
dj[(1,2)]=5
print(dj)
# can also construct all at once
dk={300:'c', 600:'d', 'cde':1, (1,2):5}
# print it out by iterating over keys
for k in dk.keys():
print(k, dk[k])
print()
# print by iterating over (key,value) pairs
for k,v in dk.items():
print(k,v)
if, else, elif
loops using for & while
List comprehensions: inline for statement
[ < do something with i > for i in data]
statement1=statement2=statement3=True
statement2=False
if (statement1):
if (statement2):
print ('both statements are true')
elif (statement3):
print ('statement2 is wrong but statement3 is true')
for x in range(-3,3,1):
print(x)
ls=['scientific','computing','in','Python']
for word in ls:
print(word)
for i,word in enumerate(ls):
print('At index',i, 'we have string',word)
i=0
while i<5:
print(i)
i=i+1
l1=[x**2 for x in range(0,5)]
print(l1)
def
docstring
, i.e., a string at the begining, which explains what the function doesdef funca(s):
"""Print a string and tell how many characters it has.
Returns the length
"""
print(s,'has',len(s),'characters')
return len(s)
print(funca('This string'))
help(funca)
If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called keyword arguments, and is often very useful in functions that takes a lot of optional arguments.
def funca(s,prnt=False,extra='p'):
"""Print a string with extra attached,
and returns new string.
"""
sn = s+extra
if prnt:
print(sn,'has',len(sn),'characters')
return sn
funca('This str', extra='ing')
In Python we can also create unnamed functions, using the lambda keyword:
f1 = lambda x: x**2
# is equivalent to
def f2(x):
return x**2
f1(3), f2(3)
This technique is useful for example when we want to pass a simple function as an argument to another function, like this:
from scipy import integrate
integrate.quad(lambda x: x**2,0,1)
A class can contain attributes (variables) and methods (functions).
A class is defined by class
keyword, and the class can contains a number of class method definitions (a function in a class).
__init__
: Constructor, i.e., the name of the method that is invoked when the object is first created.__str__
: A method that is invoked when a simple string representation of the class is needed, as for example when printed.__repr__
: Representation of the class when printed__call__
: Functor, i.e, called when the instance is “called” as a functionclass Point:
"""
Simple class for representing a point in a Cartesian coordinate system.
"""
def __init__(self, x, y):
"""
Create a new Point at x, y.
"""
self.x = x
self.y = y
def translate(self, dx, dy):
"""
Translate the point by dx and dy in the x and y direction.
"""
self.x += dx
self.y += dy
def __str__(self):
return("Point at [%f, %f]" % (self.x, self.y))
def __call__(self):
return self.x,self.y
p = Point(1.,2.)
print( p )
p.translate(1,1)
print(p)
p()
For additional modularity, modules are provided in Python.
The modularity in Python is:
Module is a python file (*.py
) or a module created by compiler (*.so
)
Outside jupyter (in regular python) we just create a file with the code, and call it a module.
Within jupyter, we need to write code into a file, and than load the module (file).
%%file mymodule.py
# This will write the following content into a file
"""
Example of a python module. Contains a variable called my_variable,
a function called my_function, and a class called MyClass.
"""
my_variable = 0
def my_function():
"""
Example function
"""
return my_variable
class MyClass:
"""
Example class.
"""
def __init__(self):
self.variable = my_variable
def set_variable(self, new_value):
"""
Set self.variable to a new value
"""
self.variable = new_value
def get_variable(self):
return self.variable
if __name__ == '__main__':
"test the module"
m = MyClass()
m.set_variable(1.)
print(m.get_variable())
!cat mymodule.py
import mymodule
help(mymodule)
m = mymodule.MyClass()
m.set_variable(10)
m.get_variable()