Chapter 5 conditions, loops, and other statements
More information about print and import
>>> print 'Age:',42Age: 42>>> print 'Age;';42Age;42>>> name = 'Gumby'>>> salutation = 'Mr'>>> greeting = 'Hello,'>>> print greeting,salutation,nameHello, Mr Gumby
>>> import math as foobar>>> foobar.sqrt(4)2.0>>> from math import sqrt as foobar>>> foobar(4)2.0
Assign value magic
>>> x,y,z = 1,2,3>>> print x,y,z1 2 3>>> x,y = y,x>>> print x,y,z2 1 3>>> values = 1,2,3>>> values(1, 2, 3)>>> x,y,z = values>>> x1>>> y2>>> >>> scoundrel = {'name':'Robin','girlfriend':'Marion'}>>> key,value = scoundrel.popitem()>>> key'girlfriend'>>> value'Marion'
Chained assignment
>>> x = y = 1>>> x1>>> y1>>>
Incremental assignment
>>> x = 2>>> x += 1>>> x3>>> x *= 4>>> x12>>> fnord = 'foo'>>> fnord += 'bar'>>> fnord'foobar'>>> fnord *=2>>> fnord'foobarfoobar'>>>
Statement block: ease of play
Condition and Condition Statement
>>> TrueTrue>>> FalseFalse>>> True == 1True>>> False == 0True>>> True + False + 4344>>> >>> bool('I think, therefore I am')True>>> bool(42)True>>> bool('')False>>> bool("")False>>> bool(0)False>>> bool([])False>>> bool({})False>>> bool(False)False>>> bool(None)False>>>
Conditional execution and if statements (if, elif, else)
name = raw_input('What is your name?')if name.endswith('Gumby'): print 'Hello, Mr.Gumby'
num = input('Enter a number:')if num > 0: print 'The number is positive'elif num < 0: print 'The number is negative'else: print 'The number is zero'
Nested code block
name = raw_input('What is your name?')if name.endswith('Gumby'): if name.startswith('Mr'): print 'Hello, Mr.Gumby' elif name.startswith('Mrs'): print 'Hello, Mrs.Gumby' else: print 'Hello, Gumby'else: print 'Hello, stranger'
More complex conditions
Comparison Operators
>>> 'foo' == "foo"True>>> 'foo' == 'bar'False>>> x = y = [1,2,3]>>> z = [1,2,3]>>> x == yTrue>>> x is yTrue>>> x is zFalse>>> x = z>>> x ==zTrue>>> >>> x = [1,2,3]>>> y = [2,4]>>> x is not yTrue>>> del x[2]>>> x[1, 2]>>> y[1] = 1>>> y.reverse()>>> y[1, 2]>>> x == yTrue>>> x is yFalse
name = raw_input('What is your name?')if 's' in name: print 'Your name contains the letter "s".'else: print 'Your name doesn\'t contain the letter "s".'
>>> "alpha" < "beta"True>>> 'FnOrD'.lower() == 'Fnord'.lower()True>>> [1,2] < [2,1]True>>> [2,[1,4]] < [2,[1,5]]True
number = input('Enter a number between 1 and 10:')if number <= 10 and number >= 1: print 'Great'else: print 'Wrong'
Assertions
Loop
While Loop
x = 1while x <= 1000: print x x += 1
name = ''while not name: name = raw_input('Please enter your name?')print 'Hello, %s!' % name
For Loop
words = ['this','is','an','ex','parrot']for word in words: print word
numbers = [0,1,2,3,4,5,6,7,8,9]for number in numbers: print number
>>> range(0,10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>
d = {'x':1,'y':2,'z':3}for key in d: print key, 'corresponds to', d[key]
y corresponds to 2x corresponds to 1z corresponds to 3
Some iteration tools
names = ['anne','beth','george','damon']ages = [12,45,32,102]for i in range(len(names)): print names[i],'is',ages[i],'year old'
Flip and sort Iteration
>>> sorted([4,3,6,8,3])[3, 3, 4, 6, 8]>>> sorted('Hello, world!')[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
Skip Loop
Break
from math import sqrtfor n in range(99,0,-1): root = sqrt(n) if root == int(root): print n break
>>> range(0,10,2)[0, 2, 4, 6, 8]>>>
Continue
While True/break
word = 'dummy'while word: word = raw_input('Please enter a word:') print 'The word was ' + word
word = raw_input('Please enter a word:')while word: print 'The word was ' + word word = raw_input('Please enter a word:')
while True: word = raw_input('Please enter a word:') if not word:break print 'The word was ' + word
from math import sqrtfor n in range(92,99,1): root = sqrt(n) if root == int(root): print n break else: print "Didn't find it!",n
Didn't find it! 92Didn't find it! 93Didn't find it! 94Didn't find it! 95Didn't find it! 96Didn't find it! 97Didn't find it! 98
from math import sqrtfor n in range(99,89,-1): root = sqrt(n) if root == int(root): print n break else: print "Didn't find it!",n
Didn't find it! 99Didn't find it! 98Didn't find it! 97Didn't find it! 96Didn't find it! 95Didn't find it! 94Didn't find it! 93Didn't find it! 92Didn't find it! 91Didn't find it! 90
The range function does not include the following boundary ~
List derivation-lightweight Loop
>>> [x*x for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> [x*x for x in range(10) if x % 3 == 0][0, 9, 36, 81]>>> [(x,y) for x in range(3) for y in range(3)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
result = []for x in range(3): for y in range(3): result.append((x,y))print result
>>> girls = ['alice','bernice','clarice']>>> boys = ['chris','arnold','bob']>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]['chris+clarice', 'arnold+alice', 'bob+bernice']
Comparison (Python judges the statement relationship based on Indentation)
result = []for x in range(3): for y in range(3): result.append((x,y))print result
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
result = []for x in range(3): for y in range(3): result.append((x,y)) print result
[(0, 0)][(0, 0), (0, 1)][(0, 0), (0, 1), (0, 2)][(0, 0), (0, 1), (0, 2), (1, 0)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Chapter 6 Abstraction
fibs = [0,1]num = input('How many Fibonacci numbers do you want?')for i in range(num-2): fibs.append(fibs[-2] + fibs[-1])print fibs
How many Fibonacci numbers do you want?10[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Function
def hello(name): return 'Hello,'+name+'!'
>>> print hello('world')Hello,world!>>> print hello('Gumby')Hello,Gumby!
def fibs(num): result = [0,1] for i in range(num-2): result.append(result[-2]+result[-1]) return result
>>> fibs(10)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]>>> fibs(10)[2]1
Record Function
def square(x): 'Calculates the square of the number x.' return x*x
def square(x): 'Calculates the square of the number x.' return x*x
Functions that are not real functions
def test(): print 'This is printed' return print 'This is not'
>>> x = test()This is printed>>> x>>> print xNone>>>
Parameter magic
>>> def change(n):n = 'Alex'>>> name = 'mr'>>> change(name)>>> name'mr'
>>> def change(n):n[0] = 'Mr. Gumby'>>> names = ['Mrs. Entity','Mrs. Thing']>>> change(names)>>> names['Mr. Gumby', 'Mrs. Thing']>>> >>> names = ['Mrs. Entity','Mrs. Thing']>>> n = names>>> n[0] = 'Mr. Gumby'>>> names['Mr. Gumby', 'Mrs. Thing']>>>
>>> names = ['Mrs. Entity','Mrs. Thing']>>> n = names>>> n is namesTrue>>> n == namesTrue>>> n = names[:]>>> n is namesFalse>>> n == namesTrue
Is True when pointing to the same object; otherwise, it is False.