Working with Tuples, Lists, and Arrays
❘
69
print(‘\nDisplaying the ragged array.’)
print(‘X Y Value’)
for x in range(len(MyList)):
if type(MyList[x]).__name__ == ‘list’:
for y in range(len(MyList[x])):
print x, y, ‘ ‘, MyList[x][y]
else:
print x, ‘N/A’, MyList[x]
In this case, the code simply checks the type of the
MyList
element before it performs any additional
processing on it. Notice that this technique relies on the
type()
function, which returns the actual
type of the element, and then you obtain the string form of the type using the
__name__
attribute.
The results are the same as shown in Figure 4-8.
Processing Arrays using the break and else Clauses
When you process sequences and arrays using loops, you sometimes need to stop what you’re doing. For
example, if you find the answer to the question of whether a number is prime or not, you really don’t
need to continue the loop that was looking for the answer. At this point, you can simply print out the
two numbers that result in the target number when multiplied. Then again, you might complete the
loop without finding a divisor that can divide equally into the number you’re testing, so you need to tell
the user that you have, indeed, found a prime number. Listing 4-9 shows one solution to this problem.
lISTINg 4-9:
Using break and else to process sequences
# Create a loop for detecting prime numbers.
for Number in range(1, 10):
# This loop looks for divisors.
for Divisor in range(2, Number):
# If the number can be divided by the divisor evenly.
if Number % Divisor == 0:
# Print the values and then exit the loop.
print Number, ‘=’, Divisor, ‘*‘, Number/Divisor
break
else:
# If you can’t divide the number by any of the divisors,
# it’s prime.
print Number, ‘is a prime number’
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
The code begins by looking at the numbers 1 through 9. (Remember that
range()
won’t output
10 in this case.) What you have at the beginning of the second loop is a number that you want to
examine. You know that you need to check all numbers smaller than the target number to determine
whether they divide evenly into the target number. For example, if you were detecting whether 4 is a
prime number, you wouldn’t try using 5 as a divisor.
548592c04.indd 69
2/24/10 12:47:37 PM
www.finebook.ir
Do'stlaringiz bilan baham: |