Answer to Question #120961 in Python for Lebenis

Question #120961
Describe the for loop and compare with the for-each loop by describing the operation of each and
discussing how they differ from each other. You must include the role of enums in your description and
provide an example of a for loop and a for-each loop.
1
Expert's answer
2020-06-09T14:15:48-0400

For i in range(), here i is the value based on the range.

Print first 8 natural numbers using for loop.

We use for loop by using range function, then we can able to run the for loop.

Range take 3 parameters: first parameter inital value, second parameter exclusive terminal value and third paramter is increment or decrement based on the usage.


for i in range(1,9,1):
   print (i)


Output:






For-each.

For-each must be need list or touple or set based on the we can iterate each element in the list like enumerate.

Print each value in the list using for-each like statement in python.


datalist = [1,2,3,4,5,6,7,8]   
for i in datalist:
    print(i)


Output:



Enumerate example.

By using enumerate we can able to access the list element position as well as list element value so based on the sample source code in python


datalist = [1,2,3,4,5,6,7,8]   
for indpos, val in enumerate (datalist):
    print(str (indpos) + "\t" + str(val))


Output:





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS