-5

There is a really differ between while and for in python? Or can I use anyone I want? And my second question :-

persons['alic', 'sam', 'rain']
first_name = 'mike'
for first_name in persons :
    #when the program runs for the first time
    #what is the value of first_name?
    #is it 'mike',or its value is Null??

    print(first_name)

And thanks.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
Ar.as
  • 31
  • 1
  • 3
  • 2
    Please ask only one question per question! – Klaus D. Apr 01 '21 at 04:24
  • `for in` and `while` both are loops of different kind. They exists because of different use cases. – Rifat Bin Reza Apr 01 '21 at 04:27
  • About your second question: When you start the program `first_name` doesn't exist. Then with `first_name = 'mike'` you define it as a string with the content `mike`. If you try to do `print(first_name)` in the first line of your code you'll see what happens. – Matthias Apr 01 '21 at 06:39

1 Answers1

1

In general, a for in loop is useful for iteration over a known set and the number of iterations is predetermined. A while loop is generally used when the exit condition is a change of state, not a predetermined length.

Common use cases for while loops include:

Running the main loop of a program until a keyboard interrupt:

    try:
        while True:
            break
    except KeyboardInterrupt:
        print("Press Ctrl-C to terminate while statement")
        pass

Finding the last node in a list of references:

while(node is not None):
    node = node.next()

This question is answered well in this stackoverflow

Pulling out the information:

while loop - used for looping until a condition is satisfied and when it is unsure how many times the code should be in loop

for loop - used for looping until a condition is satisfied but it is used when you know how many times the code needs to be in loop

do while loop - executes the content of the loop once before checking the condition of the while.