In [ ]:
print "Hello World!"
In [ ]:
print 'Hello World!'
In [ ]:
# This is a comment.
print 'This is not a comment.'
In [ ]:
'Something smells funny.'
There are four distinct numeric types in Python:
In [ ]:
print 2 + 2
In [ ]:
# Spaces between characters don't matter
print 2+2
In [ ]:
2 + 2
In [ ]:
print "2 + 2"
In [ ]:
print 2.1 + 2 # The most precise value is a float.
In [ ]:
(3.*10. - 26.)/5.
In [ ]:
(3*10 - 26)/5.0
In [ ]:
# Since our most precise value is an int, python spits out the solution as an int
(3*10 - 26)/5
In [ ]:
# Rounding errors can creep in
2.1 + 2 == 4.0999999999999996 # two 'equals' signs asks whether something is equal
In [ ]:
complex(1,2)
In [ ]:
# note that python uses j to denote the imaginary part
1+2j
In [ ]:
a = 1+2j
print a.real, a.imag
In [ ]:
1+2j-2j
In [ ]:
t = 1.0 # declare a variable t (time)
accel = 9.8 # acceleration in units of m/s^2
dist = 0.5*accel*t*t # distance traveled in time t seconds is 1/2*a*t^2
print dist # this is the distance in meters
In [ ]:
dist1 = accel*(t**2)/2 # note: t^2 means something very different!
print dist1
In [ ]:
dist2 = 0.5*accel*pow(t,2)
print dist2
In [ ]:
In [ ]:
# Integer division prints the floor; i.e., it only takes the integer digits
print 6/5
In [ ]:
# modulo operator
6 % 5
In [ ]:
# bitwise operators: shift left
# 1 in binary is '1', shifting left by two bits gives '100' = 4
1 << 2
In [ ]:
# bitwise operators: shift right
# 5 in binary is '101', shifting right by one bit gives '10' = 2
5 >> 1
In [ ]:
x = 2 ; y = 3 # multiple commands on the same line, separated by a semicolon
x | y # bitwise OR
# x in binary is '10', y in binary is '11', x | y is '11' -> 3
In [ ]:
x ^ y # exclusive OR ('10' ^ '11' = '01' = 1)
In [ ]:
x & y # bitwise AND ('10' & '11' = '10' = 2)
In [ ]:
x = x ^ y ; print x # x has been reassigned
In [ ]:
x += 3 ; print x # 'x += 3' is the same as saying 'x = x+3'
# the equivalent holds from -, *, /
In [ ]:
In [ ]:
a = 3 ; b = 4
a == b # two '=' signs for comparison, one '=' for assignment
In [ ]:
a+1 == b
In [ ]:
a+1.0 == b
In [ ]:
a < 10
In [ ]:
a < 3
In [ ]:
a <= 3
In [ ]:
a < (10 + 2j)
In [ ]:
a < -2.0
In [ ]:
a != 3.1415
In [ ]:
In [ ]:
0 == False # False is equivalent to 0, and other things
In [ ]:
1 == True # True is equivalent to 1, and other things
In [ ]:
not False
In [ ]:
1 == False
In [ ]:
not (10.0 - 10.0)
In [ ]:
x = None # None is neither True nor False
print None == False
print None == True
In [ ]:
type(None)
In [ ]:
In [ ]:
print type(1)
In [ ]:
print type("1")
In [ ]:
x = 2 ; type(x)
In [ ]:
type(2) == type(1)
In [ ]:
type(False)
In [ ]:
type(type(1))
In [ ]:
type(pow)
In [ ]:
isinstance(1,int) # check if something is a certain type
In [ ]:
isinstance("spam",str)
In [ ]:
isinstance(1.212,int)
Built-in types in python: int, bool, str, float, complex, long ...
In [ ]:
In [ ]:
x = "spam" ; print type(x)
In [ ]:
print "Hello!\nI'm hungry." # '\n' means 'new line'
In [ ]:
# This doesn't work.
print "Hello!
I'm hungry."
In [ ]:
print "Hello! \n I'm hungry."
In [ ]:
"Wah?!" == "Wah?!"
In [ ]:
print "'Wah?!' said the student."
In [ ]:
print ""Wah?!" said the student."
In [ ]:
print '"Wah?!" said the student.'
In [ ]:
print "\"Wah?!\" said the student."
Backslashes ( \ ) start special (escape) characters:
\n = newline
\r = return
\t = tab
\a = bell
String literals are defined with double (") or single quotes (').
The outermost type of quotation mark cannot be used inside a string -- UNLESS it's escaped with a backslash.
See http://docs.python.org/reference/lexical_analysis.html#string-literals
In [ ]:
# Raw strings don't recognize escape characters
print r'This is a raw string ... newlines \n are ignored. So are returns \r and tabs \t.'
In [ ]:
# Triple quotes are useful for multiple line strings
y = '''Four score and seven minutes ago,
you folks all learned some basic mathy stuff with Python
and boy were you blown away!'''
print y
In [ ]:
# Prepending 'u' makes a string "unicode"
print u"\N{BLACK HEART SUIT}"
In [ ]:
# You can concatenate strings with the '+' sign
s = "spam" ; e = "eggs"
print s + e
In [ ]:
print s + " and " + e
In [ ]:
print "green " + e + " and " + s
In [ ]:
# You can do multiple concatenations with the '*' sign
print s*3 + e
In [ ]:
print "*"*50
In [ ]:
# Strings can be compared
print "spam" == "good"
In [ ]:
# s comes before z in the alphabet
"spam" < "zoo"
In [ ]:
# 's' comes before 'spam' in the dictionary
"s" < "spam"
In [ ]:
# 'spaa' comes before 'spam' alphabetically
"spaaaaaaaaaaaam" < "spam"
In [ ]:
print 'I want ' + 3 + ' eggs and no ' + s
In [ ]:
# We have to cast the 3 (an int) as a string
print 'I want ' + str(3) + ' eggs and no ' + s
In [ ]:
pi = 3.14159 # There are easier ways to call pi, which we'll see later
print 'I want ' + str(pi) + ' eggs and no ' + s
In [ ]:
print str(True) + ':' + ' I want ' + str(pi) + ' eggs and no ' + s
In [ ]:
print s
print len(s) # len() tells you the length of a string (or, more generally, an array)
In [ ]:
print len("eggs\n") # The newline \n counts as ONE character
print len("") # empty string
In [ ]:
# Strings act like arrays. We'll see more about arrays later.
s = "SPAM"
print s
print s[0] # Python uses zero-based indexing; i.e., it starts counting at zero
print s[1]
print s[-1]
print s[-2]
In [ ]:
# Take slices of strings
print s
print s[0:1]
print s[1:4]
print s[0:100] # Python doesn't warn you. Be careful!
In [ ]:
# Slice counting backwards
print s
print s[-3:-1]
In [ ]:
# You don't have to specify both ends
print s
print s[:2]
print s[2:]
In [ ]:
# You can slice in different steps
print s
print s[::2]
print s[::-1]
Strings are immutable (unlike in C), so you cannot change a string in place.
In [ ]:
mygrade = 'F+'
print mygrade
In [ ]:
mygrade[0] = 'A'
In [ ]:
mygrade = 'A+'
print mygrade
In [ ]:
# Ask for user input
faren = raw_input("Enter the temperature (in Fahrenheit): ")
print "Your temperature is " + faren + " degrees."
In [ ]:
# User input is always saved as a string
faren = raw_input("Enter the temperature in Fahrenheit): ")
cel = 5./9. * (faren - 32.)
print "The temperature in Celcius is " + cel + " degrees."
In [ ]:
# Don't forget to convert things to the right type
faren = raw_input("Enter the temperature in Fahrenheit): ")
faren = float(faren) # The calculation on the right gets saved to the variable on the left
cel = 5./9. * (faren - 32.)
print "The temperature in Celcius is " + str(cel) + " degrees."
In [ ]:
x = raw_input("Enter x: ")
x = float(x)
print x
In [ ]:
This is a good of place as any to introduce the show that you can run you don't HAVE to use the notebook.
Everyone should have a file called temperature.py, open the file in your text editor (emacs, vim, notepad) of choice at look at its content. You will see it the same code as from the previous example. Let's try running it with the execfile command.
In [ ]:
execfile("temperature.py")
With python as in other languages you can separate scripts and programs containing python code that can be used independently or with other python programs. The notebook is excellent for code development and presentations but not the best for production level code.
In [ ]:
x = 1
print x
In [ ]:
x = 1
if x > 0: # colons indicate the beginning of a control statement
print "yo"
else: # unindenting tells Python to move to the next case
print "dude"
print "ok" # unindenting also tells Python the control statement is done
IPython Notebook automatically converts tabs into spaces, but some programs do not. Be careful not to mix these up! Be consistent in your programming.
If you're working within the Python interpreter (not the IPython Notebook), you'll see this:
>>> x = 1
>>> if x > 0:
... print "yo"
... else:
... print "dude"
... print "ok"
...
yo
ok
In [ ]:
# You can mix indentations between different blocks ... but this is ugly and people will judge you
x = 1
if x > 0:
print "yo"
else:
print "dude"
print "dude"
In [ ]:
# You can put everything on one line
print "yo" if x > 0 else "dude"
In [ ]:
# Multiple cases
x = -100
if x < -10:
print "yo"
elif x > 10: # 'elif' is short for 'else if'
print "dude"
else:
print "sup"
In [ ]:
for x in range(5,50,10):
print x**2
In [ ]:
for x in ("all","we","wanna","do","is","eat","your","brains"):
print x
In [ ]:
x = 0
while x < 5:
print pow(2,x)
x += 1 # don't forget to increment x!
In [ ]:
# Multiple levels
for x in range(1,10):
if x % 2 == 0:
print str(x) + " is even."
else:
print str(x) + " is odd."
In [ ]:
# Blocks cannot be empty
x = "fried goldfish"
if x == "spam for dinner":
print "I will destroy the universe"
else:
# Nothing here.
In [ ]:
# Use a 'pass' statement, which indicates 'do nothing'
x = "fried goldfish"
if x == "spam for dinner":
print "I will destroy the universe"
else:
pass
In [ ]:
# Use a 'break' statement to escape a loop
x = 0
while True:
print x**2
if x**2 >= 100:
break
x +=1
In [ ]:
Write a program that allows the user to build up a sentence one word at a time, stopping only when they enter a period (.), exclamation (!), or a question mark (?).
Example interaction:
Please enter a word in the sentence (enter . ! or ? to end): Call
...currently: Call
Please enter a word in the sentence (enter . ! or ? to end): me
...currently: Call me
Please enter a word in the sentence (enter . ! or ? to end): Mr
...currently: Call me Mr
Please enter a word in the sentence (enter . ! or ? to end): Tibbs
...currently: Call me Mr Tibbs
Please enter a word in the sentence (enter . ! or ? to end): !
--->Call me Mr Tibbs!
In [ ]: