Python: For and While Loop

Python day 19:

Question:
What are the ways to build and print various lists?

Usually, we use For-Loop/While-Loop to do repetitive commands. 

For-loop only iterates a collection of things, A while-loop can iteration as long as the universe. 

Example:
Create a list from 0 to 5.

For Loop Code

for i in range (0,6):
    print ("adding %d to the list" %i)
    elements.append(i)

Output:

n=0 
number=[]
while n <6:
    n=n+1
    number.append(n)
    print("adding %d to the list" %n)

Note: I had to kill the kernel twice when I was running the While-Loop because it is easy to execute as infinite loops.

Summarize:

While-Loop is fancier but more challenging to write.
For- Loop can get the majority of the things done right.

Happy study

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social media & sharing icons powered by UltimatelySocial
%d bloggers like this: