And here is the new typing exercise for this chapter:
onetoten=range(1,11)forcountinonetoten:print(count)
and the ever-present output:
12345678910
The output looks awfully familiar but the program code looks different. The first line uses therange function. Therange function uses two arguments like thisrange(start, finish).start is the first number that is produced.finish is one larger than the last number. Note that this program could have been done in a shorter way:
forcountinrange(1,11):print(count)
The range function returns an iterable. This can be converted into a list with thelist function. Here are some examples to show what happens with therange command:
>>>range(1, 10)range(1, 10)>>>list(range(1, 10))[1, 2, 3, 4, 5, 6, 7, 8, 9]>>>list(range(-32, -20))[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]>>>list(range(5,21))[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]>>>list(range(5))[0, 1, 2, 3, 4]>>>list(range(21, 5))[]
The next linefor count in onetoten: uses thefor control structure. Afor control structure looks likefor variable in list:.list is gone through starting with the first element of the list and going to the last. Asfor goes through each element in a list it puts each intovariable. That allowsvariable to be used in each successive time thefor loop is run through. Here is another example (you don't have to type this) to demonstrate:
demolist=['life',42,'the universe',6,'and',7,'everything']foritemindemolist:print("The current item is:",item)
The output is:
The current item is: lifeThe current item is: 42The current item is: the universeThe current item is: 6The current item is: andThe current item is: 7The current item is: everything
Notice how thefor loop goes through and sets item to each element in the list. So, what isfor good for? The first use is to go through all the elements of a list and do something with each of them. Here's a quick way to add up all the elements:
list=[2,4,6,8]sum=0fornuminlist:sum=sum+numprint("The sum is:",sum)
with the output simply being:
The sum is: 20
Or you could write a program to find out if there are any duplicates in a list like this program does:
list=[4,5,7,8,9,1,0,7,10]list.sort()prev=Noneforiteminlist:ifprev==item:print("Duplicate of",prev,"found")prev=item
and for good measure:
Duplicate of 7 found
Okay, so how does it work? Here is a special debugging version to help you understand (you don't need to type this in):
l=[4,5,7,8,9,1,0,7,10]print("l = [4, 5, 7, 8, 9, 1, 0, 7, 10]","\t\tl:",l)l.sort()print("l.sort()","\t\tl:",l)prev=l[0]print("prev = l[0]","\t\tprev:",prev)dell[0]print("del l[0]","\t\tl:",l)foriteminl:ifprev==item:print("Duplicate of",prev,"found")print("if prev == item:","\t\tprev:",prev,"\titem:",item)prev=itemprint("prev = item","\t\tprev:",prev,"\titem:",item)
with the output being:
l = [4, 5, 7, 8, 9, 1, 0, 7, 10] l: [4, 5, 7, 8, 9, 1, 0, 7, 10]l.sort() l: [0, 1, 4, 5, 7, 7, 8, 9, 10]prev = l[0] prev: 0del l[0] l: [1, 4, 5, 7, 7, 8, 9, 10]if prev == item: prev: 0 item: 1prev = item prev: 1 item: 1if prev == item: prev: 1 item: 4prev = item prev: 4 item: 4if prev == item: prev: 4 item: 5prev = item prev: 5 item: 5if prev == item: prev: 5 item: 7prev = item prev: 7 item: 7Duplicate of 7 foundif prev == item: prev: 7 item: 7prev = item prev: 7 item: 7if prev == item: prev: 7 item: 8prev = item prev: 8 item: 8if prev == item: prev: 8 item: 9prev = item prev: 9 item: 9if prev == item: prev: 9 item: 10prev = item prev: 10 item: 10
The reason I put so manyprint statements in the code was so that you can see what is happening in each line. (By the way, if you can't figure out why a program is not working, try putting in lots of print statements in places where you want to know what is happening.) First the program starts with a boring old list. Next the program sorts the list. This is so that any duplicates get put next to each other. The program then initializes aprev(ious) variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next afor loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value ofprev is then changed so that the next time thefor loop is run throughprev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. (Notice how\t is used to print a tab.)
The other way to usefor loops is to do something a certain number of times. Here is some code to print out the first 9 numbers of the Fibonacci series:
a=1b=1forcinrange(1,10):print(a,end=" ")n=a+ba=bb=n
with the surprising output:
1 1 2 3 5 8 13 21 34
Everything that can be done withfor loops can also be done withwhile loops butfor loops give an easy way to go through all the elements in a list or to do something a certain number of times.
In this example the Linkbot will play changing tones a fixed number of times while the duration remains constant. The Linkbot can also change tone and duration a fixed number of times. Here we are using a for loop running with in a fixed range of values.
setBuzzerFrequency.py
importbarobodongle=barobo.Dongle()dongle.connect()robot=dongle.getLinkbot('6wbn')# Replace '6wbn' with the serial ID on your Linkbotimporttime# For time.sleep()t=1# Set a value to be used for the duration of the noteforiinrange(33,43):# Select which keys on a piano keyboard to use for the tonesk=pow(2,(i-49)/12)*440# Determines the frequency of the note to be playedrobot.setBuzzerFrequency(k)# Directs the Linkbot to play this frequencytime.sleep(t)# Pauses the program while the note is playedrobot.setBuzzerFrequency(0)# Turns off the piezo speaker at the end of the program
When you run this example play around with the loop range and time values to create interesting sounds.
| Learning Python 3 with the Linkbot | ||
| ← Lists | For Loops | Boolean Expressions → |