01_BasicTraining

In [1]:
print "Hello World!"
Hello World!

Calculator

In [2]:
print 2 + 2
4
In [3]:
2 + 2
Out[3]:
4
In [4]:
print 2.1 + 2
4.1
In [5]:
2.1 + 2 == 4.0999999999999996
Out[5]:
True

Longs and complex types

In [6]:
2L
Out[6]:
2L
In [7]:
2L + 2
Out[7]:
4L
In [8]:
2L/2
Out[8]:
1L
In [9]:
2L/2.0
Out[9]:
1.0
In [10]:
complex(1,2)
Out[10]:
(1+2j)
In [11]:
1+2j
Out[11]:
(1+2j)
In [12]:
1 + 2j - 2j
Out[12]:
(1+0j)
  • variables are assigned on the fly
  • multiplication, division, exponents as you expect
In [13]:
(3.0*10.0 - 25.0)/5.0
Out[13]:
1.0
In [14]:
print 3.085e18*1e6  # this is a Megaparsec in units of cm!
3.085e+24
In [15]:
t = 1.0  # declare a variable t (time)
accel = 9.8  # acceleration in units of m/s^2
# distance travelled in time t seconds is 1/2 a*t**2
dist = 0.5*accel*t*t
print dist # this is the distance in meters
4.9
In [16]:
dist1 = accel*(t**2)/2
print dist1
4.9
In [17]:
dist2 = 0.5*accel*pow(t,2)
print dist2
4.9

Some Mathy Operators

In [18]:
print 6 / 5 ; print 9 / 5 #  integer division returns the floor
1
1
In [19]:
6 % 5 # mod operator
Out[19]:
1
In [20]:
1 << 2 ## shift: move the number 1 by two bits to the left
           ##        that is make a new number 100 (base 2)
Out[20]:
4
In [21]:
5 >> 1 ## shift: move the number 5 = 101 (base 2) one to
           ## to the right (10 = 2)
Out[21]:
2
In [22]:
x = 2 ; y = 3  ## assign two variables on the same line!
x | y          ## bitwise OR
Out[22]:
3
In [23]:
x ^ y          ## exclusive OR (10 ^ 11 = 01)
Out[23]:
1
In [24]:
x & y          ## bitwise AND
Out[24]:
2
In [25]:
x = x ^ y ; print x
1
In [26]:
x += 3 ; print x
4
In [27]:
x /= 2.0
print x
2.0

Testing Relationships

In [28]:
dist1 = 4.9 ; dist = 4.9
dist1 == dist
Out[28]:
True
In [29]:
dist < 10
Out[29]:
True
In [30]:
dist <= 4.9
Out[30]:
True
In [31]:
dist < (10 + 2j)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/jbloom/Classes/python-bootcamp/DataFiles_and_Notebooks/01_BasicTraining/<ipython-input-31-8db11a0aca8e> in <module>()
----> 1 dist < (10 + 2j)

TypeError: no ordering relation is defined for complex numbers
In [32]:
dist < -2.0
Out[32]:
False
In [33]:
dist != 3.1415 # in the future you could use math.pi
Out[33]:
True

More on Variables & Types

None, numbers and truth
In [34]:
0 == False
Out[34]:
True
In [35]:
not False
Out[35]:
True
In [36]:
0.0 == False
Out[36]:
True
In [37]:
not (10.0 - 10.0)
Out[37]:
True
In [38]:
not -1
Out[38]:
False
In [39]:
not 3.1415
Out[39]:
False
In [40]:
x = None    # None is something special. Not true or false
print None == False
print None == True
print None == None
False
False
True
In [41]:
print False or True
print False and True
True
False

More on Variables & Types

In [42]:
print type(1)
<type 'int'>
In [43]:
x = 2 ; print type(x)
<type 'int'>
In [44]:
type(2) == type(1)
Out[44]:
True
In [45]:
print type(True)
<type 'bool'>
In [46]:
print type(type(1))
<type 'type'>
In [47]:
print type(pow)
<type 'builtin_function_or_method'>

we can test whether something is a certain type with isinstance()

In [48]:
print isinstance(1,int)
print isinstance("spam",str)
print isinstance(1.212,int)
True
True
False

builtin-types: int, bool, str, float, complex, long....

Strings

In [49]:
x = "spam" ; type(x)
Out[49]:
str
In [50]:
print "hello!\n...my sire."
hello!
...my sire.
In [51]:
"hello!\n...my sire."
Out[51]:
'hello!\n...my sire.'
In [52]:
"wah?!" == 'wah?!'
Out[52]:
True
In [53]:
print "'wah?!' said the student"
'wah?!' said the student
In [54]:
print "\"wah?!\" said the student"
"wah?!" said the student

backslashes (\) start special (escape) characters:

 \n   = newline  (\r = return)
 \t   = tab
 \a   = bell

string literals are defined with double quotes or quotes. the outermost quote type cannot be used inside the string (unless it's escaped with a backslash)

In [55]:
# raw strings don't escape characters
print r'This is a raw string...newlines \r\n are ignored.'
This is a raw string...newlines \r\n are ignored.
In [56]:
# Triple quotes are real useful for multiple line strings
y = '''For score and seven minutes ago,
    you folks all learned some basic mathy stuff with Python
    and boy were you blown away!'''
print y
For score and seven minutes ago,
    you folks all learned some basic mathy stuff with Python
    and boy were you blown away!
  • prepending r makes that string "raw"
  • triple quotes allow you to compose long strings
  • prepending u makes that string "unicode"

http://docs.python.org/reference/lexical_analysis.html#string-literals

In [57]:
s = "spam" ; e = "eggs"
print s + e
spameggs
In [58]:
print s + " and " + e
spam and eggs
In [59]:
print "green " + e + " and\n " + s
green eggs and
 spam
In [60]:
print s*3 + e
spamspamspameggs
In [61]:
print "*"*50
**************************************************
In [62]:
print "spam" is "good" ; print "spam" is "spam"
False
True
In [63]:
"spam" < "zoo"
Out[63]:
True
In [64]:
"s" < "spam"
Out[64]:
True
  • you can concatenate strings with + sign
  • you can do multiple concatenations with the * sign
  • strings can be compared
In [65]:
print 'I want' + 3 + ' eggs and no ' + s
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/jbloom/Classes/python-bootcamp/DataFiles_and_Notebooks/01_BasicTraining/<ipython-input-65-91d89321074a> in <module>()
----> 1 print 'I want' + 3 + ' eggs and no ' + s

TypeError: cannot concatenate 'str' and 'int' objects
In [66]:
print 'I want ' + str(3) + ' eggs and no ' + s 
I want 3 eggs and no spam
In [67]:
pi = 3.14159
print 'I want ' + str(pi) + ' eggs and no ' + s
I want 3.14159 eggs and no spam
In [68]:
print str(True) + ":" + ' I want ' + str(pi) + ' eggs and no ' + s
True: I want 3.14159 eggs and no spam

you must concatenate only strings, coercing ("casting") other variable types to str

We can think of strings as arrays (although, unlike in C you never really need to deal with directly addressing character locations in memory)

In [69]:
s = 'spam'
len(s)
Out[69]:
4
In [70]:
len("eggs\n")
len("")
Out[70]:
0
In [71]:
print s[0]
print s[-1]
s
m
  • len() gives us the length of an array
  • strings are zero indexed
  • can also count backwards

Flow is done within blocks (where indentation matters)

In [72]:
x = 1
if x > 0:
    print "yo"
else:
    print "dude"
yo
In [73]:
x = 1
if x > 0:
    print "yo"
else:
        print "dude"
yo

One liners

In [74]:
print "yo" if x > 0 else "dude"
yo

case statements can be constructed with just a bunch of if, elif,...else

In [75]:
if x < 1:
     print "t"
elif x > 100:
     print "yo"
else:
     print "dude"
dude

ordering matters. The first block of True in an if/elif gets executed then everything else does not.

blocks cannot be empty

In [76]:
x = "fried goldfish"
if x == "spam for dinner":
    print "I will destroy the universe"
else:
    # I'm fine with that. I'll do nothing
IndentationError: expected an indented block
In [77]:
x = "fried goldfish"
if x == "spam for dinner":
    print "I will destroy the universe"
else:
    # I'm fine with that. I'll do nothing
    pass

pass is a "do nothing"/NOP statement

In [77]: