In [1]:
# this block is just for the style sheet for the notebook
from IPython.core.display import HTML
def css_styling():
styles = open("styles/custom.css", "r").read()
return HTML(styles)
css_styling()
Out[1]:
From your textbook:
"...climbs the hierarchy to the next level of Python program structure:
At their base, programs written in the Python language are composed of statements and expressions. Expressions process objects and are embedded in statements. Statements code the larger logic of a program’s operation—they use and direct expressions to process the objects we studied in the preceding chapters. Moreover, statements are where objects spring into existence (e.g., in expressions within assignment statements), and some statements create entirely new kinds of objects (functions, classes, and so on). At the top, statements always exist in modules, which themselves are managed with statements."
In [15]:
# simple if statement
x = 1
y = 2
if x < y: # parentheses around the logical expression are optional
x = 2
y = 1
print x,y
In [19]:
# when to use parentheses
A = 1
B = 2
C = 3
if (A == 1 and
B == 2 and
C == 3):
print 'yes '*3
In [20]:
# if/else
A = 1
B = 2
C = 3
if (A == 1 and # here we used line continuation
B == 2 and
C == 4):
print 'yes '*3
else:
print 'no '*3
In [22]:
# if and if-else
# if/else
A = 1
B = 2
C = 3
if (A == 1 and
B == 2 and
C == 4):
print 'yes '*3
elif (A == 1 and
B == 2 and
C == 3):
print 'maybe ' * 3
else:
print 'no '*3
In [24]:
# line continuation
A = 1
B = 2
C = 3
# avoid this - if there is space after the / you'll get an error
X = A + \
B + C
print X
# instead use this
X = (A +
B + C)
print X
In [26]:
# special if statement
# here the body of the if statement is a single statement
A = 1
if A == 1: print A
In [28]:
import sys
print sys.version
In [34]:
S = """
aaaa
bbbb #xyz
cccc"""
print S
In [36]:
S = ('aaaa'
'bbbb' # Comments here are ignored
'cccc')
print S
In [37]:
L = ["Good",
"Bad",
"Ugly"]
print L
In [1]:
# define a dictionary
branch = {'spam': 1.25, 'ham': 1.99,'eggs': 0.99}
In [2]:
# use the get function
branch.get('spamd', 'Bad Choice')
Out[2]:
In [3]:
# print the dictionary as a list of tuples
branch.items()
Out[3]:
In [4]:
# loop though dictionary and print key-value pairs
for (key,value) in branch.items():
print key, '\t', value
In [2]:
# simple while loop
x='spam'
while x:
print x,
x=x[1:]
In [7]:
# some formatting
print '%02d' % (1,)
In [11]:
# some more formatting
x=3.1415926
print '{:.2f}'.format(x)
In [12]:
# simple assignments
a = 3
b = a
print a,b
a = 4
print a,b
In [5]:
# list copying and assigning
L=[1,2,3,4]
L1 = L
print L,L1
L.append(5)
print L, L1
L1 = L[:] # deep copy
L.append(6)
print L, L1
In [ ]: