| Author: | Christopher Haynes |
|---|---|
| Email: | chaynes@indiana.edu |
| Affiliation: | Indiana University |
| Course: | BL CSCI A201 |
| Date: | 2008-02-21 |
>>> def fun(param):
local_var = 3
print local_var, param, global_var
>>> global_var = 4 >>> fun(2) 3 2 4
>>> def fun2():
print local_var
>>> fun2() Traceback (most recent call last): File "", line 1, in ? File " ", line 2, in fun2 NameError: global name 'local_var' is not defined >>> def fun3(): global_var = 5 # this actually creates a local variable print global_var
>>> fun3() 5 >>> global_var 4

def powers(n):
"""
Prints a table of the first n integers and the corresponding
power of two.
>>> powers(10)
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
>>>
"""
i = 1
while i <= n:
print i, 2**i
i = i + 1
Most loops exit when the value of a variable referenced in the loop's test expression changes in a way that makes the expression false
In an accumulator loop one or more variables store the result of accumulating (gathering) information in the loop
For Example, an accumulator sentinel loop that prints the product of the input numbers. Transcript:
Enter number, or Enter to exit: 3 Enter number, or Enter to exit: 2.5 Enter number, or Enter to exit: -23.6 Enter number, or Enter to exit: Product = -177.0
Solution: product.py
# product.py, by chaynes@indiana.edu
# input a series of numbers and print their product
product = 1
while True:
text = raw_input('Enter number, or to exit: ')
if text == '':
break
product = product * float(text) # same as: product *= float(text)
print 'Product =', product
def powers_acc(n):
"""
Same as powers(n), but use an accumulator and not the
exponentiation operator.
Hint: initialize the accumulator to 2 and multiply it by
two with each iteration.
>>> powers_acc(3)
1 2
2 4
3 8
>>>
"""
#.
#.
#.
#.
#.
#.
def powers_acc(n):
"""
Same as powers(n), but use an accumulator and not the
exponentiation operator.
Hint: initialize the accumulator to 2 and multiply it by
two with each iteration.
>>> powers_acc(3)
1 2
2 4
3 8
>>>
"""
i = 1
accumulator = 2
while i <= n:
print i, accumulator
accumulator = accumulator * 2
i = i + 1
If a function f is supposed to return a value (other than None), must f contain a return statement in its body?Answer: A
If a function f is supposed to print a value, must f contain a print statement in its body?Answer: B
Which of the following defines a global variable named x containing 3?Answer: C
Which of the following is not a Python comparison operator?Answer: E
The value of 2<1 or not 2<3 and 3<4 isAnswer: B
The ordinal suffix of 1, 2, and 3 is st, nd, and rd, respectively, while that of integers larger than 3 and less than 21 is th
Define the function ordinal_form(n) that returns a string consisting of n followed by its ordinal suffix assuming n is an integer in the range from 1 through 20
>>> ordinal_form(3) '3rd' >>> ordinal_form(1) '1st' >>> ordinal_form(10) '10th' >>> ordinal_form(2) '2nd'
def ordinal_form(n):
# assume n is an integer in the range from 1 through 20
if n == 1:
return '1st'
elif n == 2:
return '2nd'
elif n == 3:
return '3rd'
else:
return str(n) + 'th'
Which of the following is true just when x is in the range from 0 to 10, inclusive of both endpoints?Answer: C
How would you rate the first assignment?
How are you doing in the current assignment?
How would you rate the last lab?>>> print 'line 1\nline 2' line 1 line 2 >>> print 'a\ttab' a tab >>> print 'He said "What?"' He said "What?" >>> print "That's ok" That's ok >>> print 'He said "That\'s ok"' He said "That's ok" >>> print "He said \"That's ok\"" He said "That's ok" >>> print "dir\\subdir" dir\subdir >>> 'dir\\subdir' 'dir\\subdir' >>> 'a\xy' ValueError: invalid \x escape
>>> 'one string' + 'and another' 'one stringand another' >>> print 'Answer: ' + 3.14 * 5 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot concatenate 'str' and 'float' objects >>> print 'Answer: ' + str(3.14 * 5) Answer: 15.7 >>> 'Answer: ' + 42 TypeError: cannot concatenate 'str' and 'int' objects >>> 'Answer: ' + str(42) 'Answer: 42' >>> int(' 3\n') 3 >>> int('1 + 2') ValueError: invalid literal for int(): 1 + 2 >>> len('py') 2 >>> len('') 0 >>> 'NI' * 3 'NININI' >>> ' ' * 5 ' ' >>>
The multiplication table would look better if the columns were aligned
In chapter 6 of your text, this is done using tab (\t) characters, but this is undesirable because tabs skip some fixed amount that may not be what you want and depends on how printing is done
Tabs also left justifies columns, whereas numbers look better when right justified
for example, the first column below is left justified, and the second is right justified:
1 1 12 12 123 123
def right_justify(n, string): """ Returns the string with enough blanks added at the beginning to make it n characters long. >>> right_justify(5, 'foo') ' foo' >>> """ return ' ' * (n - len(string)) + stringFYI Python, like most languages, has a somewhat complicated formatting mechanism that allows justification and some other formatting possibilities to be expressed in a very compact way. But that's beyond this course, and sometimes you still have to know how to do it yourself anyway.
def mult_table(n):
"""
Print an n by n multiplication table.
>>> mult_table(9)
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
>>>
"""
i = 1
while i <= n:
j = 1
line = ''
while j <= n:
line = line + str(i * j) + ' '
j = j + 1
print line
i = i + 1
def justified_mult_table(n, width):
"""
Print an n by n multiplication table in which each column has
the indicated width.
>>> justified_mult_table(9, 4)
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
>>>
"""
i = 1
while i <= n:
j = 1
line = ''
while j <= n:
#...
j = j + 1
print line
i = i + 1
def justified_mult_table(n, width):
"""
Print an n by n multiplication table in which each column has
the indicated width.
>>> justified_mult_table(9, 4)
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
>>>
"""
i = 1
while i <= n:
j = 1
line = ''
while j <= n:
line = line + right_justify(width, str(i * j))
j = j + 1
print line
i = i + 1
def powers_formatted(n):
"""
Prints a table of the first n integers and the corresponding
power of two.
Right justify the integers in two columns and the power in 6,
with a space between the columns.
>>> powers_formatted(10)
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
>>>
"""
i = 1
while i <= n:
#...
#...
print formatted_i, formatted_power
i = i + 1
def powers_formatted(n):
"""
Prints a table of the first n integers and the corresponding
power of two.
Right justify the integers in two columns and the power in 6,
with a space between the columns.
>>> powers_formatted(10)
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
>>>
"""
i = 1
while i <= n:
formatted_i = right_justify(2, str(i))
formatted_power = right_justify(6, str(2**i))
print formatted_i, formatted_power
i = i + 1
The module fpformat has a function fix(x, digs) that takes a number x and a positive integer digs (for "digits") and returns a floating point string with digs digits after the decimal point.
>>> import fpformat >>> fpformat.fix(2.58, 1) '2.6' >>> fpformat.fix(-2.0 / 3, 3) '-0.667' >>> fpformat.fix(3, 4) '3.0000'
This can be used in combination with a string justification function to right or left justify floating point numbers.