Iteration, while loop, and for loop
Veek M
vek.m1234 at gmail.com
Thu Oct 27 05:05:00 EDT 2016
Elizabeth Weiss wrote:
> words=["hello", "world", "spam", "eggs"]
> counter=0
> max_index=len(words)-1
>
> while counter<=max_index:
> word=words[counter]
> print(word + "!")
> counter=counter + 1
while 0 < 10:
get 0'th element
do something with element
increment 0 to 1
(repeat)
words[0] gets the 0'th word (arrays/lists start at 0, not 1)
--------------------
That example of his is badly presented..
1. use i, x, y, z, count in that order for integers
2. do your dirty work in a function
3. keep loops clean and tidy
4. keep data far away from code
5. avoid " when ' does the trick
6. try to create black box functions - that work no matter what you
throw at them.. without sacrificing readability - programming is about
aesthetics and readability - quite artsy..
(I'm not an expert so.. some of this might be outright wrong)
words=['hello', 'world', 'spam', 'eggs']
def display(txt, decoration='!'):
message = str(txt) + str(decoration)
print(message)
i = 0
i_max = len(words) - 1
while i <= i_max:
word = words[i]
i += 1
display(word)
languages that don't have 'for' like C, will use 'while' - in python
'for' is preferred - faster, readable - especially for the example you
cited.
More information about the Python-list
mailing list