This notebook was put together by [Jake Vanderplas](http://www.vanderplas.com) for UW's [Astro 599](http://www.astro.washington.edu/users/vanderplas/Astr599/) course. Source and licensing info is on [GitHub](https://github.com/jakevdp/2013_fall_ASTR599/).
In [1]:
print "Hello World!"
http://www.roesler-ac.de/wolfram/hello.htm
file: hello.py
print "Hello World!"
[~]> python hello.py
file: hello.java
class HelloWorld {
static public void main( String args[] ) {
System.out.println( "Hello World!" );
}
}
[~]> javac hello.java
[~]> java HelloWorld
Hello World!
file: hello.cpp
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
}
[~]> g++ -o hello hello.cpp
[~]> ./hello
Hello World!
file: hello.f
PROGRAM HELLO
WRITE (*,100)
STOP
100 FORMAT (' Hello World! ' /)
END
[~]> g77 -o hello hello.f
[~]> ./hello
Hello World!
int
: integerfloat
: floating point (decimal)long
: long integercomplex
: complex number (decimal, not integer)+
: addition-
: subtraction/
: division*
: multiplication%
: modulus (remainder)**
: exponentiationAs we go through this, note carefully how these operations interact with various types
In [2]:
print 2 + 2
In [3]:
2 + 2
Out[3]:
In [1]:
print 2.1 + 2
Careful: floats are limited by their 16-bit representation (same as in other languages)
In [8]:
print 4.0999999999999995
In [6]:
2.1 + 2 == 4.0999999999999995
Out[6]:
In [19]:
4 * 2
Out[19]:
In [14]:
4 / 2
Out[14]:
In [15]:
5 / 2
Out[15]:
Integer operations result in integers (floor of the float result): this can cause unexpected problems!
Fix this by using floats when dividing.
In [43]:
9 / 5
Out[43]:
In [44]:
9.0 / 5 # result will be a float
Out[44]:
In [17]:
5 % 2 # modulus (remainder after division)
Out[17]:
In [18]:
5 ** 2
Out[18]:
In [105]:
# or you can use the pow() function
pow(5, 2)
Out[105]:
In [11]:
print 2 + 2
3 + 3
In [12]:
print 1 + 1 # easy arithmetic
In [6]:
2L
Out[6]:
In [7]:
2L + 2
Out[7]:
In [8]:
2L/2
Out[8]:
In [9]:
2L/2.0
Out[9]:
In [10]:
complex(1,2)
Out[10]:
In [11]:
1+2j
Out[11]:
In [12]:
1 + 2j - 2j
Out[12]:
In [13]:
(3.0*10.0 - 25.0)/5.0
Out[13]:
In [14]:
print 3.085e18 * 1e6 # this is a Megaparsec in units of cm!
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
In [16]:
dist1 = accel*(t**2)/2
print dist1
In [17]:
dist2 = 0.5*accel*pow(t,2)
print dist2
A nice trick that other languages can't do:
In [3]:
x, y = 4, 50
print x
print y
In [4]:
x, y = y, x # easy swap!
print x
print y
Each operator has an operate-and-assign version
In [52]:
x = 4
x += 8 # same as x = x + 8
print x
In [53]:
x *= 0.2 # x is upgraded to a float!
print x
In [55]:
x %= 1
print x
In [26]:
bin(14) # print binary representation
Out[26]:
In [27]:
14 << 1
Out[27]:
In [28]:
bin(14 << 1)
Out[28]:
In [29]:
14 >> 1
Out[29]:
In [38]:
bin(14 >> 1)
Out[38]:
In [31]:
14 & 4
Out[31]:
In [39]:
print bin(14), bin(4), bin(14&4)
In [32]:
14 & 1
Out[32]:
In [36]:
14 | 1
Out[36]:
In [40]:
print bin(14), bin(1), bin(14|1)
In [41]:
14 | 4
Out[41]:
In [35]:
14 ^ 4
Out[35]:
In [42]:
print bin(14), bin(4), bin(14^4)
In [56]:
x = 14
x <<= 1 # bit-shift and assign
print x
In [57]:
2 < 4
Out[57]:
In [58]:
3 >= 3
Out[58]:
In [59]:
5 == 4
Out[59]:
In [60]:
5 != 4
Out[60]:
In [90]:
5 < 2 + 4j
Comparisons can also be strung together and behave as expected:
In [76]:
x = 4
y = 6
print 2 < x <= 4
print 2 < y <= 4
In [80]:
# This allows strange/confusion expressions
# don't do things like this!
8 > x <= 5
Out[80]:
In [65]:
0.1 + 0.2 == 0.3
Out[65]:
In [70]:
# this is a string formatting command (we'll cover this later)
# it says to print 20 places after the decimal
print "%.20f" % (0.1 + 0.2)
print "%.20f" % 0.3
Moral of the story: in any language you use, be careful using equality comparisons on floating point!
In [81]:
x = 4
(x > 2) and (x < 10)
Out[81]:
In [84]:
(x <= 4) or not (x > 10)
Out[84]:
In [91]:
0 == False
Out[91]:
In [95]:
not False
Out[95]:
In [96]:
not 0
Out[96]:
In [86]:
not -1
Out[86]:
zero is evaluated to False
, every other number to True
In [98]:
print None # None is a special object
In [102]:
print None == True
print None == False
print None == None
print bool(None)
In [114]:
x = 1
y = 1
print x is y
In [120]:
False is not 2
Out[120]:
In [119]:
False is (not 2)
Out[119]:
In [126]:
x = 1111
y = 1111
print x is y
Takeaway: "is
" and "is not
" refer to the memory being used by the object.
If x
and y
point to the same location in memory, then x is y
will be True.
Probably their most common use is in comparisons to None
. All variables equal to None
are guaranteed to point to the same memory location (i.e. it acts as a Singleton).
In [127]:
x = None
print x is None
You don't need to fully understand this, but just be aware that teh is
and is not
operators should generally not be used unless you do!
In [42]:
print type(1)
In [43]:
x = 2 ; print type(x)
In [44]:
type(2) == type(1)
Out[44]:
In [45]:
print type(True)
In [103]:
print type(None)
In [46]:
print type(type(1))
In [104]:
print type(pow)
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)
builtin-types: int
, bool
, str
, float
, complex
, long
....
In [49]:
x = "spam" ; type(x)
Out[49]:
In [50]:
print "hello!\n...my sire."
In [51]:
"hello!\n...my sire."
Out[51]:
In [52]:
"wah?!" == 'wah?!'
Out[52]:
In [53]:
print "'wah?!' said the student"
In [54]:
print "\"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 (marked with r) don't escape characters
print r'This is a raw string...newlines \r\n are ignored.'
In [106]:
# 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
r
makes that string "raw"u
makes that string "unicode"http://docs.python.org/reference/lexical_analysis.html#string-literals
In [57]:
s = "spam" ; e = "eggs"
print s + e
In [58]:
print s + " and " + e
In [59]:
print "green " + e + " and\n " + s
In [60]:
print s*3 + e
In [61]:
print "*" * 50
In [1]:
print "spam" == "good" ; print "spam" == "spam"
In [63]:
"spam" < "zoo"
Out[63]:
In [64]:
"s" < "spam"
Out[64]:
+
sign*
sign
In [65]:
print 'I want' + 3 + ' eggs and no ' + s
In [66]:
print 'I want ' + str(3) + ' eggs and no ' + s
In [67]:
pi = 3.14159
print 'I want ' + str(pi) + ' eggs and no ' + s
In [68]:
print str(True) + ":" + ' I want ' + str(pi) + ' eggs and no ' + s
you must concatenate only strings, coercing ("casting")
other variable types to str
In [4]:
# Note that raw_input does not work in IPython notebook version < 1.0
# You can always do this from a file or from the command line, though
faren = raw_input("enter a temperature (in Fahrenheit): ")
print faren
In [5]:
cent = (faren - 32) / 1.8
In [7]:
cent = (float(faren) - 32) / 1.8
print cent
In [9]:
# Or in one line:
faren = float(raw_input("enter a temperature (in Fahrenheit): "))
print (faren - 32) / 1.8
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 [13]:
s = 'spam'
len(s)
Out[13]:
In [14]:
len("eggs\n")
Out[14]:
In [15]:
len("")
Out[15]:
In [16]:
print s[0]
print s[-1]
In [17]:
print s[0:1]
In [18]:
print s[1:4]
In [19]:
print s[-2:]
In [21]:
print s[0:100] # if the slice goes past the end, no complaints!
In [22]:
print s[0:4:2]
In [25]:
print s[::2]
In [26]:
print s[::-1]
len()
gives us the length of an array
In [72]:
x = 1
if x > 0:
print "yo"
else:
print "dude"
One liners
In [74]:
print "yo" if x > 0 else "dude"
In [29]:
x = 1
y = 0
while y < 10:
print "yo" if x > 0 else "dude"
x *= -1
y += 1
In [5]:
# Could also do this with a break statement
x = 1
y = 0
while True:
print "yo" if x > 0 else "dude"
x *= -1
y += 1
if y >= 10:
break
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"
elif x == 42:
print "bingo"
else:
print "dude"
Note: ordering matters. The first block of True
in an if/elif gets executed then everything else does not.
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
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 [38]:
%%file number_game.py
# The above "magic" command saves the contents
# of the current cell to file. We'll see more of these later
x = 0
max_tries = 10
count = 0
while True:
x_new = int(raw_input("Enter a new number: "))
if x_new > x:
print " -> it's bigger than the last!"
elif x_new < x:
print " ->it's smaller than the last!"
else:
print " -> no change! I'll exit now"
break
x = x_new
count += 1
if count > max_tries:
print "too many tries..."
break
In [39]:
%run number_game.py
# this magic command runs the given file
Create a program (a .py file) which repeatedly asks the user for a word. The program should append all the words together. When the user types a "!", "?", or a ".", the program should print the resulting sentence and exit.
For example, a session might look like this:
[~]$ python breakout01.py
Enter a word (. ! or ? to end): My
Enter a word (. ! or ? to end): name
Enter a word (. ! or ? to end): is
Enter a word (. ! or ? to end): Walter
Enter a word (. ! or ? to end): White
Enter a word (. ! or ? to end): !
My name is Walter White!