![]() ![]() |
| |||||||||
| Hotspots: Slides and Code TA Corner Comments? Announcements FAQ Static Webspace | ||||||||||
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
| for ___ in _____: | for number in [1, 3, 7, 8, 0, 10, 57937, 2]: print number, "squared is", (number * number) |
If you want to perform a set of code on a list of objects (in this case, finding the square of not just a number, but a list of numbers) then rather than writing the same code over and over for each object in the list, you can LOOP through the list with the same code. This is extremely useful for making a change to every pixel in a picture. So logically, if you have a list of 10 objects and you make a for loop out of it, then the code below the for loop (which is indented to denote that it is part of that for loop) will execute 10 times. The word immediately following the word for is just a random variable name that you come up with. What's the usefulness of this? You can use this variable name to refer to the current object of the current "iteration".
And after the list has been exhausted, JES will continue on to the next unindented code. For loop definitions always end in a colon. To remember the syntax just think: for item in list: | |
| Confusions & Insights: | |
| if, else, elif | if myCash > $8: print "Welcome to Moe's!" else: print "Welcome to Woodruff" |
If you want some code to only execute if some sort of condition is true, then you can surround it with an if statement. If I don't have 8 dollars then I can't go to Moe's. if is always followed by some sort of condition that is either true or false. If it's false, then the following indented code will be completely and utterly ignored. Now if you wanted some code to execute if it was true and a DIFFERENT set of code to execute if it is false but never want both sets of code executing, then you can use an else like in the example above. I've got to eat, but I'm definitely not eating at both Moe's and Woodruff. So if I have $8 I will go to Moe's, but if I don't, then I'll have to settle for overly flammable pizza. else never has a condition after it. if always has a condition after it. There's also something called elif which works like else, but has a condition after it. This is useful if you have more than just two sets of options. Look at this example... if myCash > $8:print "Welcome to Moe's" elif myCash > $4: print "Welcome to Taco Bell" else: print "Welcome to Woodruff" Hopefully that example is enough to explain the purpose of elif. Note: when JES is going through your if's and elif's, it will go with the FIRST one it finds with a true condition. Once it executes the corresponding code, it'll skip over everything else in the list of elif's and else's. That means if I have $10, I won't eat at both Moe's and Taco Bell, I'll just eat at Moe's. | |
| Confusions & Insights: | |