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_2014/) course. Source and licensing info is on [GitHub](https://github.com/jakevdp/2014_fall_ASTR599/).
In [122]:
%run talktools.py
In [123]:
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 [124]:
print(2 + 2)
In [125]:
2 + 2
Out[125]:
In [126]:
print(2.1 + 2)
Careful: floats are limited by their 16-bit representation (same as in other languages)
In [127]:
print(4.0999999999999995)
In [128]:
2.1 + 2 == 4.0999999999999995
Out[128]:
In [129]:
4 * 2
Out[129]:
In [130]:
4 / 2
Out[130]:
In [131]:
5 / 2 # Note this is different in Python 2.x!!
Out[131]:
In [132]:
5 // 2
Out[132]:
Integer operations result in integers in Python 2.x, but floats in Python 3.x.
In [133]:
5 % 2 # modulus (remainder after division)
Out[133]:
In [134]:
5 ** 2
Out[134]:
In [135]:
# or you can use the pow() function
pow(5, 2)
Out[135]:
In [136]:
print(2 + 2)
3 + 3
In [137]:
print(1 + 1) # easy arithmetic
In [138]:
complex(1,2)
Out[138]:
In [139]:
1+2j
Out[139]:
In [140]:
1 + 2j - 2j
Out[140]:
In [141]:
(3.0*10.0 - 25.0)/5.0
Out[141]:
In [142]:
print(3.085e18 * 1e6) # this is a Megaparsec in units of cm!
In [143]:
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 [144]:
dist1 = accel*(t**2)/2
print(dist1)
In [145]:
dist2 = 0.5*accel*pow(t,2)
print(dist2)
A nice trick that other languages can't do:
In [146]:
x, y = 4, 50
print(x)
print(y)
In [147]:
x, y = y, x # easy swap!
print(x)
print(y)
Each operator has an operate-and-assign version
In [148]:
x = 4
x += 8 # same as x = x + 8
print(x)
In [149]:
x *= 0.2 # x is upgraded to a float!
print(x)
In [150]:
x %= 1
print(x)
In [151]:
bin(14) # print binary representation
Out[151]:
In [152]:
bin(13)
Out[152]:
In [153]:
14 & 13
Out[153]:
In [154]:
bin(14 & 13)
Out[154]:
In [155]:
14 | 13
Out[155]:
In [156]:
bin(14 | 13)
Out[156]:
In [157]:
2 < 4
Out[157]:
In [158]:
3 >= 3
Out[158]:
In [159]:
5 == 4
Out[159]:
In [160]:
5 != 4
Out[160]:
In [161]:
5 < 2 + 4j
Comparisons can also be strung together and behave as expected:
In [162]:
x = 4
y = 6
print(2 < x <= 4)
print(2 < y <= 4)
In [163]:
# This allows strange/confusion expressions
# don't do things like this!
8 > x <= 5
Out[163]:
In [164]:
0.1 + 0.2 == 0.3
Out[164]:
In [165]:
# this is a string formatting command (we'll cover this later)
# it says to print 20 places after the decimal
print("{0:.20f}".format(0.1 + 0.2))
print("{0:.20f}".format(0.3))
Moral of the story: in any language you use, be careful using equality comparisons on floating point!
In [166]:
x = 4
(x > 2) and (x < 10)
Out[166]:
In [167]:
(x <= 4) or not (x > 10)
Out[167]:
In [168]:
0 == False
Out[168]:
In [169]:
not False
Out[169]:
In [170]:
not 0
Out[170]:
In [171]:
not -1
Out[171]:
zero is evaluated to False
, every other number to True
In [172]:
print(None) # None is a special object
In [173]:
print(None == True)
print(None == False)
print(None == None)
print(bool(None))
In [174]:
x = 1
y = 1
x is y
Out[174]:
In [175]:
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 [176]:
x = None
print(x is None)
You don't need to fully understand this, but just be aware that the is
and is not
operators should generally not be used unless you do!
In [177]:
print(type(1))
In [178]:
x = 2
print(type(x))
In [179]:
type(2) == type(1)
Out[179]:
In [180]:
print(type(True))
In [181]:
print(type(None))
In [182]:
print(type(type(1)))
In [183]:
print(type(pow))
we can test whether something is a certain type with isinstance()
In [184]:
print(isinstance(1, int))
print(isinstance("spam", str))
print(isinstance(1.212, int))
builtin-types: int
, bool
, str
, float
, complex
, long
....
In [185]:
x = "spam" ; type(x)
Out[185]:
In [186]:
print("hello!\n...my sire.")
In [187]:
"hello!\n...my sire."
Out[187]:
In [188]:
"wah?!" == 'wah?!'
Out[188]:
In [189]:
print("'wah?!' said the student")
In [190]:
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 [191]:
# raw strings (marked with r) don't escape characters
print(r'This is a raw string...newlines \r\n are ignored.')
In [192]:
# 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 [193]:
s = "spam" ; e = "eggs"
print(s + e)
In [194]:
print(s + " and " + e)
In [195]:
print("green " + e + " and\n " + s)
In [196]:
print(s*3 + e)
In [197]:
print("*" * 50)
In [198]:
print("spam" == "good"); print("spam" == "spam")
In [199]:
"spam" < "zoo"
Out[199]:
In [200]:
"s" < "spam"
Out[200]:
+
sign*
signBut you can't add strings and integers:
In [201]:
print('I want' + 3 + ' eggs and no ' + s)
In [202]:
print('I want ' + str(3) + ' eggs and no ' + s)
In [203]:
pi = 3.14159
print('I want ' + str(pi) + ' eggs and no ' + s)
In [204]:
print(str(True) + ":" + ' I want ' + str(pi) + ' eggs and no ' + s)
you must concatenate only strings, coercing ("casting")
other variable types to str
In [205]:
# 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 = input("enter a temperature (in Fahrenheit): ")
print(faren)
(Note that in Python 2.x you should use raw_input
rather than input
Remember that the input comes as a string:
In [206]:
cent = (faren - 32) / 1.8
In [207]:
cent = (float(faren) - 32) / 1.8
print(cent)
In [208]:
# Or in one line:
faren = float(input("enter a temperature (in Fahrenheit): "))
(faren - 32) / 1.8
Out[208]:
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 [209]:
s = 'spam'
len(s)
Out[209]:
In [210]:
len("eggs\n")
Out[210]:
In [211]:
len("")
Out[211]:
In [212]:
print(s[0])
print(s[-1])
In [213]:
s[0:1]
Out[213]:
In [214]:
s[1:4]
Out[214]:
In [215]:
s[-2:]
Out[215]:
In [216]:
s[0:100] # if the slice goes past the end, no complaints!
Out[216]:
In [217]:
s[0:4:2]
Out[217]:
In [218]:
s[::2]
Out[218]:
In [219]:
s[::-1]
Out[219]:
len()
gives us the length of an array
In [220]:
x = 1
if x > 0:
print("yo")
else:
print("dude")
One liners
In [221]:
"yo" if x > 0 else "dude"
Out[221]:
In [222]:
x = 1
y = 0
while y < 10:
print("yo" if x > 0 else "dude")
x *= -1
y += 1
In [223]:
# 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 [224]:
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 [225]:
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 [226]:
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 [227]:
%%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(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 [229]:
%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!
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
If you finish quickly... see how few characters you can write this program in (this is known as "code golf": going for the fewest key strokes).