Python loops

Share:

Executing the same code multiple times is the use case of loop, we have two kinds of loops in Python:

While loop:
While loop is the simple form of the loop which will keep executing until its condition is true so in order to stop the while loop we have to control the condition:

                while condition:
codes
condition changer

condition changer:
we have already studied about conditions but what is a condition changer, its so simple anything which changes the condition is condition changer and since the loop is executing command each time and then it checks back the condition so we can change the condition inside the loop body, like using a variable in condition and changing it inside loop body:
                
               Var = 10
               while 0<Var:
                       print(Var)
                       Var = Var-1




For loop:
For loop in Python works with iterators that means something which is made of multiple values (complex data types), for loop will keep executing for each element in the iterator and we can access each element by the variable which is required in for loop:

                for VarName in iterator: codes

for loop don’t have any condition it will stop when it executes for each element in iterator, iterators can be one of the complex data types or range method, range method will provide a range of numbers for the for loop to iterate:

                for VarName in range(Number): codes

      Complex Data types:
      complex data types are those which are made of multiple values like string is made of multiple characters
o   str
o   list
o   dict
o   tup
o   set

No comments