This notebook was put together by Jake Vanderplas for UW's Astro 599 course. Source and licensing info is on GitHub.
%run talktools.py
Much of this material thanks to http://www.pythonbootcamp.info/
We saw before how easy a hello world script is to create in Python:
print("Hello World!")
Hello World!
http://www.roesler-ac.de/wolfram/hello.htm
file: hello.py
print "Hello World!"
file: hello.java
class HelloWorld {
static public void main( String args[] ) {
System.out.println( "Hello World!" );
}
}
file: hello.cpp
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
}
file: hello.f
PROGRAM HELLO
WRITE (*,100)
STOP
100 FORMAT (' Hello World! ' /)
END
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
print(2 + 2)
4
2 + 2
4
print(2.1 + 2)
4.1
Careful: floats are limited by their 16-bit representation (same as in other languages)
print(4.0999999999999995)
4.1
2.1 + 2 == 4.0999999999999995
True
4 * 2
8
4 / 2
2.0
5 / 2 # Note this is different in Python 2.x!!
2.5
5 // 2
2
Integer operations result in integers in Python 2.x, but floats in Python 3.x.
5 % 2 # modulus (remainder after division)
1
5 ** 2
25
# or you can use the pow() function
pow(5, 2)
25
print(2 + 2)
3 + 3
File "<ipython-input-136-25c65360fa6d>", line 2 3 + 3 ^ IndentationError: unexpected indent
# for comments¶# will be ignoredprint(1 + 1) # easy arithmetic
2
complex(1,2)
(1+2j)
1+2j
(1+2j)
1 + 2j - 2j
(1+0j)
(3.0*10.0 - 25.0)/5.0
1.0
print(3.085e18 * 1e6) # this is a Megaparsec in units of cm!
3.085e+24
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
dist1 = accel*(t**2)/2
print(dist1)
4.9
dist2 = 0.5*accel*pow(t,2)
print(dist2)
4.9
A nice trick that other languages can't do:
x, y = 4, 50
print(x)
print(y)
4 50
x, y = y, x # easy swap!
print(x)
print(y)
50 4
Each operator has an operate-and-assign version
x = 4
x += 8 # same as x = x + 8
print(x)
12
x *= 0.2 # x is upgraded to a float!
print(x)
2.4000000000000004
x %= 1
print(x)
0.40000000000000036
You might also come across bitwise operators:
&: bitwise and|: bitwise or^: bitwise xor<<: bit-shift left>>: bit-shift rightAll these make more sense if you think about binary representations:
bin(14) # print binary representation
'0b1110'
bin(13)
'0b1101'
14 & 13
12
bin(14 & 13)
'0b1100'
14 | 13
15
bin(14 | 13)
'0b1111'
==, !=: equal, not equal<, <=: less than, less than or equal>, >=: greater than, greater than or equal2 < 4
True
3 >= 3
True
5 == 4
False
5 != 4
True
5 < 2 + 4j
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-161-22831f5cf00f> in <module>() ----> 1 5 < 2 + 4j TypeError: unorderable types: int() < complex()
Comparisons can also be strung together and behave as expected:
x = 4
y = 6
print(2 < x <= 4)
print(2 < y <= 4)
True False
# This allows strange/confusion expressions
# don't do things like this!
8 > x <= 5
True
Precision issues can lead to seemingly strange results (again, this is the same in any modern programming language)
0.1 + 0.2 == 0.3
False
# 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))
0.30000000000000004441 0.29999999999999998890
Moral of the story: in any language you use, be careful using equality comparisons on floating point!
Python has two built-in boolean values, True and False which we've seen above.
There are also built-in logical operations to test these
A or B : True if either A or B or both are TrueA and B : True only if both A and B are Truenot A: True only if A is Falsex = 4
(x > 2) and (x < 10)
True
(x <= 4) or not (x > 10)
True
0 == False
True
not False
True
not 0
True
not -1
False
zero is evaluated to False, every other number to True
print(None) # None is a special object
None
print(None == True)
print(None == False)
print(None == None)
print(bool(None))
False False True False
is and is not¶x = 1
y = 1
x is y
True
x = 1111
y = 1111
print(x is y)
False
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).
x = None
print(x is None)
True
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!
print(type(1))
<class 'int'>
x = 2
print(type(x))
<class 'int'>
type(2) == type(1)
True
print(type(True))
<class 'bool'>
print(type(None))
<class 'NoneType'>
print(type(type(1)))
<class 'type'>
print(type(pow))
<class 'builtin_function_or_method'>
we can test whether something is a certain type with isinstance()
print(isinstance(1, int))
print(isinstance("spam", str))
print(isinstance(1.212, int))
True True False
builtin-types: int, bool, str, float, complex, long....
x = "spam" ; type(x)
str
print("hello!\n...my sire.")
hello! ...my sire.
"hello!\n...my sire."
'hello!\n...my sire.'
"wah?!" == 'wah?!'
True
print("'wah?!' said the student")
'wah?!' said the student
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)
# raw strings (marked with r) 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.
# 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!
r makes that string "raw"u makes that string "unicode"http://docs.python.org/reference/lexical_analysis.html#string-literals
s = "spam" ; e = "eggs"
print(s + e)
spameggs
print(s + " and " + e)
spam and eggs
print("green " + e + " and\n " + s)
green eggs and spam
print(s*3 + e)
spamspamspameggs
print("*" * 50)
**************************************************
print("spam" == "good"); print("spam" == "spam")
False True
"spam" < "zoo"
True
"s" < "spam"
True
+ sign* signBut you can't add strings and integers:
print('I want' + 3 + ' eggs and no ' + s)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-201-fbc395a7f2be> in <module>() ----> 1 print('I want' + 3 + ' eggs and no ' + s) TypeError: Can't convert 'int' object to str implicitly
print('I want ' + str(3) + ' eggs and no ' + s)
I want 3 eggs and no spam
pi = 3.14159
print('I want ' + str(pi) + ' eggs and no ' + s)
I want 3.14159 eggs and no spam
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
# 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)
enter a temperature (in Fahrenheit): 280 280
(Note that in Python 2.x you should use raw_input rather than input
Remember that the input comes as a string:
cent = (faren - 32) / 1.8
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-206-692d7634602b> in <module>() ----> 1 cent = (faren - 32) / 1.8 TypeError: unsupported operand type(s) for -: 'str' and 'int'
cent = (float(faren) - 32) / 1.8
print(cent)
137.77777777777777
# Or in one line:
faren = float(input("enter a temperature (in Fahrenheit): "))
(faren - 32) / 1.8
enter a temperature (in Fahrenheit): 232
111.11111111111111
We can think of strings as arrays (although, unlike in C you never really need to deal with directly addressing character locations in memory)
s = 'spam'
len(s)
4
len("eggs\n")
5
len("")
0
print(s[0])
print(s[-1])
s m
s[0:1]
's'
s[1:4]
'pam'
s[-2:]
'am'
s[0:100] # if the slice goes past the end, no complaints!
'spam'
s[0:4:2]
'sa'
s[::2]
'sa'
s[::-1]
'maps'
len() gives us the length of an arrayx = 1
if x > 0:
print("yo")
else:
print("dude")
yo
One liners
"yo" if x > 0 else "dude"
'yo'
x = 1
y = 0
while y < 10:
print("yo" if x > 0 else "dude")
x *= -1
y += 1
yo dude yo dude yo dude yo dude yo dude
# 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
yo dude yo dude yo dude yo dude yo dude
case statements can be constructed with
just a bunch of if, elif,...else
if x < 1:
print("t")
elif x > 100:
print("yo")
elif x == 42:
print("bingo")
else:
print("dude")
dude
Note: ordering matters. The first block of True in an if/elif gets executed then everything else does not.
x = "fried goldfish"
if x == "spam for dinner":
print("I will destroy the universe")
else:
# I'm fine with that. I'll do nothing
File "<ipython-input-225-51470879c358>", line 5 # I'm fine with that. I'll do nothing ^ SyntaxError: unexpected EOF while parsing
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
%%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
Overwriting number_game.py
%run number_game.py
# this magic command runs the given file
Enter a new number: 200 -> it's bigger than the last! Enter a new number: 200 -> no change! I'll exit now
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).