Python3 tutorial - 4
----------------------------------------------------------------------------------------------------------
Welcome to my tutorial 4,
now, we will loop around the loop structures in python3,
loops are the structures in python which enables us to repeat a task as many times as we want to,
there 2 types of loops in python3:
1. while loops
2. for loops
WHILE LOOPS:
they start with the "while" keyword and run until and unless the condition given is True,
for example:
in this picture, we can see that,
we declared a variable count and then used the while condition check, it uses continuous checking on the provided
statement and then comes the body after ":" where we print count variable and then increment its value by 1,
when going like this, there comes a point when count = 11 and the condition provided with while keyword is not met and the the while loop stops and executes the code statements written after the body,
when we will try to print value of count variable, it will print
11 at the end of the loop and if we want to use another while loop
using same count variable, we will have to declare value of count to 0 like this:
count = 0
and then we are ready to use it, but it is not the perfect way to reduce count to 0 every time we use it,
for this we will use for loop for this purpose,
Note: while loops look similar to if and elif statements but are different in a way that they keep on running until the condition is False, the moment the condition comes out to be False, they handle execution to code statements written after their body,
Note: if we will not increment the the value of count variable in a while loop, it will become an infinite loop as its value will always be less than or equal to 10 and seeing the condition True every time, while loop will execute forever,
FOR LOOPS:
start with a "for" keyword and are similar to while loops in a way,
these both looping structures are used to repeat a task or function,
but there is difference b/w them, you can see it in the following example,
for example:
here, we can see that,
we don't need to increment the value of count every time and the count variable used in for loop is temporary and its value can't be used outside the body of the for loop,
for loop uses the range() function to generate a range of numbers and the last number of the range will always be 1 less than the number specified in the function,
this example loop ran 10 times but its last value for 9 as it started from 0, remember that range() function generates a sequence of number which start from 0 and go till the value 1 less than the number specified,
lets call of this part as I feel that you are beginning to loop over while and for loops,
see you later !
Comments
Post a Comment